使用$手表没有$范围(控制器语法) [英] Using $watch without $scope ( controller as syntax)

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

问题描述

在角1.3它可以使用 $ scope.foo ='酒吧'的 this.foo ='酒吧' insteaod 。现在,我该如何使用 $观看 $没有范围?


解决方案

有几种选择,以避免使用 $观看当使用控制器语法。

下面的实施例是从<一个取href=\"http://www.technofattie.com/2014/03/21/five-guidelines-for-avoiding-scope-soup-in-angular.html\">blog后我写了关于避免 $范围

NG-变化


  

如果你有一块手表设置为监听属性变化的
  从表单域发起,然后NG-变化是你最好的选择。


 &LT;输入类型=文本NG模型=ctrl.nameNG变化=ctrl.search(ctrl.name)/&GT;MyCtrl.prototype.search =功能(名称){
  //这里调用一些服务
};

使用ES5属性


  

如果您有未绑定到输入字段,或者是某些属性
  打算从code更新,它可能看起来像一个手表是你唯一的
  选择。但是,如果你没有支持IE8或更低,那么你
  可以采取ES5特性的优势,当触发功能
  一些控制器上的变化。


  VAR MyCtrl =功能(){
  this._selectedItem = NULL;
};Object.defineProperty(MyCtrl.prototype,
    将selectedItem,{
    得到:函数(){
        返回this._selectedItem;
    },
    设置:功能(newValue)以{
        this._selectedItem =为newValue;        //更新上调用方法
        this.onSelectedItemChange(this._selectedItem);
    },
    枚举:真实,
    配置:真
});

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?

解决方案

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

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

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

Using ES5 Properties

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

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

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