使用不带$scope的$watch(作为语法的控制器)

Using $watch without $scope ( controller as syntax)

本文关键字:语法 控制器 watch scope      更新时间:2023-09-26

在Angular 1.3中,可以使用this.foo='bar'代替$scope.foo='bar'。现在,如何在没有$scope的情况下使用$watch

在使用controller as语法时,有几个选项可以避免使用$watch

下面的例子取自我写的一篇关于避免$scope的博客文章。

使用ng-change

如果你设置了一块手表来监听房产的变化源于表单字段,则ng更改是您的最佳选择。

<input type="text" ng-model="ctrl.name" ng-change="ctrl.search(ctrl.name)" />
MyCtrl.prototype.search = function(name){
  //call some service here
};

使用ES5属性

如果您有一些属性未绑定到输入字段,或者将从代码中更新,看起来手表是你唯一的选择选择然而,如果您不必支持IE8或更低版本,那么您可以利用ES5属性在以下情况下触发功能你的控制器发生了一些变化。

var MyCtrl = function(){
  this._selectedItem = null;
};
Object.defineProperty(MyCtrl.prototype,
    "selectedItem", {
    get: function () {
        return this._selectedItem;
    },
    set: function (newValue) {
        this._selectedItem = newValue;
        //Call method on update
        this.onSelectedItemChange(this._selectedItem);
    },
    enumerable: true,
    configurable: true
});