2

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.

7
  • your preferred-check-box is inside of ng-repeat ? Commented Dec 3, 2015 at 9:52
  • yes. it is inside the ng-repeat Commented Dec 3, 2015 at 9:52
  • Can you provide a fiddle ? Commented Dec 3, 2015 at 10:00
  • jsfiddle.net/tanch/rd0b1n4b/7 Commented Dec 3, 2015 at 10:15
  • when click on the text, it should change "checked" to "unchecked", vice versa Commented Dec 3, 2015 at 10:18

2 Answers 2

1

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");
        })
    }

Sign up to request clarification or add additional context in comments.

Comments

0

just add scope.$apply(); in your link function, just before the alert, to start the digest loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.