0

I my template i have:

    <md-checkbox ng-model="$ctrl.isAdOps" aria-label="isAdOps">
        isAdOps {{ $ctrl.isAdOps }}
    </md-checkbox>

In my component:

(function (app) {
    app.component('homeComponent', {
        templateUrl: 'partials/home-partial.html',
        bindings: {
            isAdOps: '='
        },
        controller: ['$scope', '$state', function ($scope, $state) {

            var self = this;

            $scope.$watch(
                self.isAdOps,
                function (isAdOps) {
                    $scope.$broadcast('isAdOpsToggled', isAdOps);
                }
            );
        }]
    });

})(myApp);

why doesn't the watch called when i toggle the md-checkbox?

bugs
  • 14,631
  • 5
  • 48
  • 52
Elad Benda2
  • 13,852
  • 29
  • 82
  • 157

2 Answers2

0

Angular $watch first parameter should of type string/function

string: Evaluated as expression

function(scope): called with current scope as a parameter.

replace self.isAdOps with 'isAdOps' in $watch or alternativly use a function syntax with $scope.

Community
  • 1
  • 1
super cool
  • 6,003
  • 2
  • 30
  • 63
0

You are better off using the ng-change directive:

<md-checkbox ng-model="$ctrl.isAdOps"
             ng-change="$ctrl.isAdOpsChanged($ctrl.isAdOps)"
             aria-label="isAdOps>
    isAdOps {{ $ctrl.isAdOps }}
</md-checkbox>

It avoids using $scope and adding a watcher.

For more information, see Writing Components without Watchers.

See also, AngularJS Developer Guide - Component-based application architecture.

Components should follow a few simple conventions:

  • Inputs should be using < and @ bindings. The < symbol denotes one-way bindings which are available since 1.5. The difference to = is that the bound properties in the component scope are not watched, which means if you assign a new value to the property in the component scope, it will not update the parent scope. Note however, that both parent and component scope reference the same object, so if you are changing object properties or array elements in the component, the parent will still reflect that change. The general rule should therefore be to never change an object or array property in the component scope. @ bindings can be used when the input is a string, especially when the value of the binding doesn't change.

  • Outputs are realized with & bindings, which function as callbacks to component events.

This will make the migration to Angular 2+ easier.

georgeawg
  • 48,608
  • 13
  • 72
  • 95