Nathan Friend Nathan Friend - 2 years ago 48
Javascript Question

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

option. Here's my directive definition (written in 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
property is correctly bound to the controller. 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):

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
event I can listen to inside this controller object that is fired after Angular has finished applying its initial binding values to this object?

Answer Source

There is no such event and there's none should be, because one-way @ binding means that myScopeProperty value may be updated multiple times.

$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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download