angular 1.5:当我切换 ui 时,手表不调用

angular 1.5: watch doesn't call when i toggle the ui

我有我的模板:

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

在我的组件中:

(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);

为什么当我切换 md-checkbox 时手表没有调用?

Angular $watch 第一个参数应该是 string/function

string: Evaluated as expression

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

在 $watch 中将 self.isAdOps 替换为 'isAdOps' 或在 $scope 中使用函数语法。

你最好使用 ng-change 指令:

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

它避免了使用 $scope 和添加观察者。

有关详细信息,请参阅

另见,AngularJS Developer Guide - Component-based application architecture

组件应遵循一些简单的约定:

  • 输入应该使用 <@ 绑定。 < 符号表示 one-way bindings 从 1.5 开始可用。与 = 的不同之处在于组件作用域中的绑定属性不受监视,这意味着如果您为组件作用域中的 属性 分配新值,它不会更新父作用域。但是请注意,父作用域和组件作用域都引用同一个对象,因此如果您正在更改组件中的对象属性或数组元素,父作用域仍会反映该更改。因此,一般规则应该是永远不要更改组件范围内的对象或数组 属性。 @ 当输入是字符串时可以使用绑定,尤其是当绑定的值不变时。

  • 输出是通过 & 绑定实现的,它作为组件事件的回调。

这将使迁移到 Angular 2+ 更容易。