Reputation: 5848
How can i simply add and remove checked attribute to check-box using angularjs. I've find solution from this question,but it requires Jquery
Is any other way to do this without using Jquery?
Here is what i am tried
<input type="checkbox" id="test" class="switch__input" checked="{{checkVal}}">
<input type="button" ng-click="test()" value="test">
JS
module.controller('settingsCtrl',function($scope){
//for adding
$scope.checkVal="checked";
//for removing checkbox
$scope.test=function(){
$scope.CheckVal="";
}
}
But the removing wont work
Upvotes: 8
Views: 14375
Reputation: 2767
This is Angularjs recommended way of check and un check checkbox
HTML :
<input type="checkbox" ng-model="checkVal" ng-true-value="true" ng-false-value="false">
Also works
<input type="checkbox" ng-checked="checkVal">
JS :
module.controller('settingsCtrl',function($scope){
//for adding
$scope.checkVal=true;
//for removing checkbox
$scope.test=function(){
$scope.checkVal=false;
}
}
Upvotes: 7
Reputation: 1293
Please check working example : DEMO
HTML
<input type="checkbox" id="test" class="switch__input" ng-checked="checkVal">
<input type="button" ng-click="test()" value="test">
Controller:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.checkVal = true;
//for adding/removing checkbox
$scope.test = function() {
$scope.checkVal = !$scope.checkVal;
}
});
Upvotes: 1
Reputation: 193261
You don't need special directive for this, ngChecked would work well:
var app = angular.module('demo', []).controller('MainController', function($scope) {
$scope.checkVal = true;
$scope.test = function() {
$scope.checkVal = !$scope.checkVal; // or false
};
});
<script src="https://code.angularjs.org/1.4.3/angular.js"></script>
<div ng-app="demo" ng-controller="MainController">
<input type="checkbox" id="test" class="switch__input" ng-checked="checkVal">
<input type="button" ng-click="test()" value="test">
</div>
Upvotes: 1
Reputation: 2232
I can across a directive to add dynamic attribute may be this can help you
myApp.directive('dynAttr', function() {
return {
scope: { list: '=dynAttr' },
link: function(scope, elem, attrs){
for(attr in scope.list){
elem.attr(scope.list[attr].attr, scope.list[attr].value);
}
//console.log(scope.list);
}
};
});
In the controller
$scope.attArray = [
{ attr: 'myattribute', value: '' }
];
Use it as
<input dyn-attrs="attArray"></input>
Upvotes: 0