使用没有$ scope的$ watch(控制器作为语法)

PHP*_*Pst 13 javascript watch angularjs

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

Jos*_*osh 19

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

以下示例摘自我撰写的关于避免$scope博客文章.

运用 ng-change

如果您设置的手表可以监听来自表单字段的属性更改,那么ng-change是您最好的选择.

<input type="text" ng-model="ctrl.name" ng-change="ctrl.search(ctrl.name)" />

MyCtrl.prototype.search = function(name){
  //call some service here
};
Run Code Online (Sandbox Code Playgroud)

使用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
});
Run Code Online (Sandbox Code Playgroud)