使用不带 $scope 的 $watch (控制器作为语法) [英] Using $watch without $scope ( controller as syntax)

查看:24
本文介绍了使用不带 $scope 的 $watch (控制器作为语法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Angular 1.3 it's possible to use this.foo='bar' insteaod of $scope.foo='bar'. Now, how can I use $watch without $scope?

推荐答案

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

There are several options to avoid having to use $watch when using the controller as syntax.

以下示例取自 我写的关于避免 $scope 的博文.

The following examples are taken from a blog post I wrote about avoiding $scope.

使用ng-change

如果您设置了一个手表来监听属性变化源自表单字段,那么 ng-change 是您最好的选择.

If you have a watch set up to listen for a property change that originates from a form field, then ng-change is your best bet.

<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 属性在以下情况下触发功能您的控制器发生了一些变化.

If you have some property that isn't bound to an input field, or is going to be updated from code, it may seem like a watch is your only choice. However, if you don't have to support IE8 or lower, then you can take advantage of ES5 properties to trigger functionality when something changes on your controller.

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

这篇关于使用不带 $scope 的 $watch (控制器作为语法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆