2

So I have a directive that has a checkbox in it. I need to make a web service call when the value of the checkbox is changed. How can I get the value of that checkbox when it is clicked? I want the checkbox confined to the scope of the directive.

myModule.directive('test', function() {
    return {
        restrict: 'A',
        replace: true,
        scope:{},
        template:   
            '<div>'+
                '<input type="checkbox" ng-click="toggleRoomLock()" name="lockRoom" value="lock" ng-model="lockRoom">'+
            '</div>',
        link: function(scope, element, attrs) {
            scope.toggleRoomLock = function(){
                //GET VALUE OF CHECKBOX HERE
            };
        }
    }
}

I have tried getting the value using scope.lockRoom but I am getting undefined. Any suggestions?

2 Answers 2

5

The easiest way is to remove the ng-click attribute from the template and put a watch on the model. Change the link function to:

function (scope, element, attrs) {
    scope.lockRoom = false; // initialize to unchecked

    scope.$watch('lockRoom', function (value) {
        // value will contain either true or false depending on checked state
    });
}

$watch allows you to listen to changes on your models (basically objects added to scope).

Example plunker (value logged to console).

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

2 Comments

So i just tried what you suggested and it's not triggering the $watch when i click.
Compare it with the plunker I added. If you still can't get it to work please create a plunker and I'll try to help you.
2

You should be able to get the value of scope.lockRoom from your toggle function:

'<input type="checkbox" ng-click="toggle()" ng-model="lockRoom">'
...
scope.toggle = function() {
   console.log('lockRoom=',scope.lockRoom)
}

Plunker

However, ng-change is usually used with checkboxes, rather than ng-click:

'<input type="checkbox" ng-change="toggle()" ng-model="lockRoom">'

Using ng-change or ng-click may be more efficient than using $watch, since the toggle() function will not be called every digest cycle, like the $watch is.

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.