简体   繁体   English

将绑定应用于控制器后是否发出Angular $ scope事件?

[英]Is there an Angular $scope event emitted after bindings have been applied to a controller?

I'm using a directive in an Angular (1.4) application that uses the bindToController option . 我在使用bindToController选项的Angular(1.4)应用程序中使用bindToController Here's my directive definition (written in TypeScript): 这是我的指令定义(用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: '@'
    };
}

This is working as expected - the myScopeProperty property is correctly bound to the controller. 这按预期方式工作myScopeProperty属性已正确绑定到控制器。 However, this binding process happens after the object is constructed, which means I can't perform any logic that depends on the value of this bound property while the object is being constructed. 但是,此绑定过程是在构造对象之后发生的,这意味着在构造对象时,我无法执行任何依赖于此绑定属性值的逻辑。 For example (again, in TypeScript): 例如(再次,在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); 
    }
}

Is there a $scope event I can listen to inside this controller object that is fired after Angular has finished applying its initial binding values to this object? 在Angular将其初始绑定值应用到该对象后,是否有一个$scope事件可以监听到该控制器对象内?

There is no such event and there's none should be, because one-way @ binding means that myScopeProperty value may be updated multiple times. 没有此类事件,也不应有此类事件,因为单向@绑定意味着myScopeProperty值可能会多次更新。

$scope.$watch('vm.myScopeProperty', () => { ... }));

is the recommended way to watch for binding changes. 是观察绑定更改的推荐方法。

$timeout(() => { ... });

or $onInit controller hook (polyfillable in 1.4. with angular-component ) may be used to to postpone the code to a time when myScopeProperty has been already interpolated (the first time). $onInit控制器挂钩 (可在1.4。中用angular-component $onInit )可用于将代码推迟到已经插值myScopeProperty的时间(第一次)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM