Dor*_*hen 35 javascript angularjs typescript angularjs-components
如何监听角度组件绑定更改并执行操作?
angular.module('myapp')
.component('myComponent', {
templateUrl: 'some.html',
controller: MyController,
controllerAs: 'myCtrl',
bindings: {
items: '<'
}
});
Run Code Online (Sandbox Code Playgroud)
现在当items
我想要使用此值执行其他操作时,我该
怎么办?
小智 59
您可以将$onChanges
方法添加到控制器
$onChanges(changesObj)
在更新单向绑定时调用.changesObj是一个哈希,其键是已更改的绑定属性的名称,值是表单的对象.
以下示例处理canChange
更改事件.
angular.module('app.components', [])
.component('changeHandler', {
controller: function ChangeHandlerController() {
this.$onChanges = function (changes) {
if (changes.canChange)
this.performActionWithValueOf(changes.canChange);
};
},
bindings: {
canChange: '<'
},
templateUrl: 'change-handler.html'
});
Run Code Online (Sandbox Code Playgroud)
需要AngularJS> = 1.5.3并且仅适用于单向数据绑定(如上例所示).
文档:https://docs.angularjs.org/guide/component
参考:http://blog.thoughtram.io/angularjs/2016/03/29/exploring-angular-1.5-lifecycle-hooks.html
bas*_*rat 27
现在当项目更改时我想使用此值执行另一个操作,我该怎么办?
但我想避免使用垂死的$ scope
如果你不希望使用$scope
,你可以使用属性setter方法来检测任何改变,例如:
class MyController {
private _items: string[] = []
set items(value:string[]){
this._items = value;
console.log('Items changed:',value);
}
get items():string[]{
return this._items;
}
}
const ctrl = new MyController();
ctrl.items = ['hello','world']; // will also log to the console
Run Code Online (Sandbox Code Playgroud)
请注意,你不应该将其用于复杂的逻辑(原因:https://basarat.gitbooks.io/typescript/content/docs/tips/propertySetters.html)
这是basarat 答案的ES5.1版本:
function MyController() {
var items = [];
Object.defineProperty(this, 'items', {
get: function() {
return items;
},
set: function(newVal) {
items = newVal;
console.log('Items changed:', newVal);
}
});
}
Run Code Online (Sandbox Code Playgroud)
使用Object.defineProperty().受所有主流浏览器和IE9 +支持.