使用$手表没有$范围(控制器语法) [英] Using $watch without $scope ( controller as syntax)
问题描述
在角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 thecontroller 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屋!