PCoelho PCoelho - 1 year ago 78
AngularJS Question

AngularJS directives attributes access from the controller

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. Is there a way to execute code only after the directive and it's scopes are ready and set to be used?

I made a fiddle with it. Make sure your console is open. http://jsfiddle.net/paulocoelho/uKA2L/1/

Here is the code I am using in the fiddle:

<div ng-app="testApp" >
<testcomponent text="hello!"></testcomponent>

var module = angular.module('testApp', [])
.directive('testcomponent', function () {
return {
restrict: 'E',
template: '<div><p>{{text}} This will run fine! </p></div>',
scope: {
text: '@text'
controller: function ($scope, $element) {
console.log($scope.text); // this will return undefined
setTimeout(function () {
console.log($scope.text); // this will return the actual value...
}, 1000);
link: function ($scope, $element, $attrs) {
setTimeout(function () {
}, 1000);


What works is, if you set

scope.text = attrs.text;

inside the linking and the controller functions.

See fiddle: http://jsfiddle.net/JohannesJo/nm3FL/2/