0

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!

Adoratus
  • 55
  • 8
  • 1
    Using `ng-model` as an attribute instantiates the [ngModelController](https://docs.angularjs.org/api/ng/type/ngModel.NgModelController). That controller is likely fighting the custom directive. Use of the `ng-` prefix is reserved for core directives. For more information, see [AngularJS Wiki - Best Practices](https://github.com/angular/angular.js/wiki/Best-Practices). – georgeawg Feb 02 '17 at 04:24
  • Thanks @georgeawg! You are right! – Adoratus Feb 03 '17 at 10:53

1 Answers1

0

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'