lundi 25 janvier 2016

Three state checkbox with angular directive

I'm new to angularjs and I'm having a very difficult time attempting to create a directive to implement a three-state checkbox. I'd like to create a two-way binding between the isolated scope variable in my directive and my controller scope variable. Obviously somehow I've cocked it up.

My goal is to be able to update the state of the checkbox in the dom whenever the state variable gets updated in the controller, and to update the state variable in the controller whenever the user clicks on the checkbox.

After snooping around on the google machine i decided I needed to set up a $watch on my directive attribute (my knowledge of which is tenuous as best). I haven't been able to get that to work. It never gets called when my variable is changed from the controller. Below is a snippet of my markup and the meat of my directive. See my fiddle below for the details.

<input checkbox-three-state='item.state' type='checkbox' /> 

directive('checkboxThreeState', ['$compile', function($compile) {
    return {
        restrict: 'A',
        scope: {
            state: '=checkboxThreeState'
        },
        link: function (scope, element, attributes) {
            element.on('click', function () {
                // update the controller scope
            });

            scope.$watch(attributes.checkboxThreeState, function (newVal, oldVal) {
                // update the dom
            });
        }
    }
}]);

I think I have my other objective (update controller scope on click) down.

Here's my fiddle.




Aucun commentaire:

Enregistrer un commentaire