Reputation: 1246
I want to build a customize checkbox by write a directive.
App.directive('preferredCheckBox', function() {
return {
restrict: 'E',
require: '?ngModel',
scope: {
ngModel: '='
},
link: function(scope, elem,attrs){
elem.bind('click', function() {
scope.ngModel = !scope.ngModel;
//alert("clicked");
})
},
template: "<div ng-if='ngModel'> <span class='ion-ios-star text-red' style='font-size:2em'></span></div> " +
"<div ng-if='!ngModel'> <span class='ion-ios-star-outline text-red' style='font-size:2em'></span></div>"
}
});
This is how I call the directive
<preferred-check-box ng-model="item.isChecked"></preferred-check-box>
The directive work fine for display purpose. But if I click on the checkbox, it doesn't change the value of "item.isChecked"
In my opinion, inside the directive :
scope: {
ngModel: '='
},
link: function(scope, elem,attrs){
elem.bind('click', function() {
scope.ngModel = !scope.ngModel;
//alert("clicked");
})
},
It just clone another "item.isChecked" value into its own local scope, during trigger the click function, it doesn't change the original "item.isChecked".
How can I handle this ? I want to pass ng-model by reference.
Here is the link : http://jsfiddle.net/tanch/rd0b1n4b/7/ When I click the text "checked", it should change to "unchecked", vice versa.
Upvotes: 2
Views: 1351
Reputation: 940
just add scope.$apply();
in your link function, just before the alert, to start the digest loop.
Upvotes: 0
Reputation: 6332
see working example: http://jsfiddle.net/kevalbhatt18/rd0b1n4b/11/
link: function(scope, elem,attrs,ngModel){
elem.bind('click', function() {
ngModel.$setViewValue(!scope.ngModel);
ngModel.$render();
alert("clicked");
})
}
Upvotes: 1