Problems with isolated scope and bindings

58 Views Asked by At

I try to build directive in which i want to change model on clicking by element. Some sort of checkbox... Here is my code

mainApp.directive('subCategory', function(){
    return{
        restrict: 'A',
        scope: {
            model: '=?ngModel'
        },
        link : function(scope, element){

            scope.model = true;
            element.click(function () {

            if (element.hasClass('active')) {
                element.removeClass('active');
                scope.model = false;
            } else {
                element.addClass('active');
                scope.model = true;
            }

         });
        }
    } 
});

Than i try to $watch group of this checkboxes in parent controller by watching object which contains ng-model properties of all checkboxes.

mainApp.controller('Filter',['$scope', function ($scope) {
$scope.data = {}

$scope.$watchCollection('data', function(newNames, oldNames) {
  console.log('changed');
});

}]);

When i define property by scope.model = true; it works and watching works, but when i change scope.model on click in some reasons it doesn't affect data object and watch doesn't work. Can someone tell me why?
Thanks!

1

There are 1 best solutions below

0
On

In your directive change

 scope: {
        model: '=?ngModel'
    },

To

  scope: {
        model: '=ngModel'
    },

as mentioned above when you pass ngModel to link function that is when you declare

 require:'?ngModel'