I am trying to access the attributes of a directive in the controller function. However, by the time I access it, it is undefined. I noticed that if I do a simple timer it works
Since Angular 1.3, you can use bindToController
. Here is a sample on how I use it. Here, I add the attribute to scope and then use bindToController
to use that inside the controller:
var module = angular.module('testApp', [])
.directive('testcomponent', function () {
return {
restrict: 'E',
template: '{{text}} This will run fine!
',
scope: {
text: '@text'
},
controller: function () {
console.log(this.text);
},
controllerAs: 'vm',
bindToController: true
};
});
Angular 1.3 introduces a new property to the directive definition object called bindToController, which does exactly what it says. When set to true in a directive with isolated scope that uses controllerAs, the component’s properties are bound to the controller rather than to the scope. That means, Angular makes sure that, when the controller is instantiated, the initial values of the isolated scope bindings are available on this, and future changes are also automatically available.