我在使用bindToController
option的Angular(1.4)应用程序中使用指令。这是我的指令定义(用TypeScript编写):
export class MyDirective implements ng.IDirective {
public restrict = 'E';
public templateUrl = 'path/to/my/template.html';
public controller = 'MyController';
public controllerAs = 'vm';
public bindToController = true;
public scope = {
myScopeProperty: '@'
};
}
这正在按预期工作 - myScopeProperty
属性正确绑定到控制器。但是,此绑定过程在构造对象后发生,这意味着在构造对象时,我无法执行任何依赖于此绑定属性值的逻辑。例如(同样,在TypeScript中):
export class MyController {
public myScopeProperty;
constructor() {
// this logs "undefined", even if the my-scope-property
// attribute on the directive has a value
console.log('myScopeProperty: ' + this.myScopeProperty);
}
}
是否有一个$scope
事件我可以在Angular完成将其初始绑定值应用于此对象后触发此控制器对象内部?
答案 0 :(得分:1)
没有这样的事件,也没有,因为单向@
绑定意味着myScopeProperty
值可能会多次更新。
$scope.$watch('vm.myScopeProperty', () => { ... }));
是观察绑定更改的推荐方法。
$timeout(() => { ... });
或$onInit
controller hook(在1.4。angular-component中可填充)可用于将代码推迟到myScopeProperty
已插入的时间(第一次)。