コントローラ関数のディレクティブの属性にアクセスしようとしています。しかし、私がそれにアクセスするまでには、それは未定義です。簡単なタイマーを使えばうまくいくことに気づきました。ディレクティブとそのスコープの準備ができて使用できるように設定された後でのみコードを実行する方法はありますか?
私はそれをいじった。コンソールが開いていることを確認してください。http://jsfiddle.net/paulocoelho/uKA2L/1/
これが私がフィドルで使用しているコードです:
<div ng-app="testApp" >
<testcomponent text="hello!"></testcomponent>
</div>
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) {
console.log($scope.text);
setTimeout(function () {
console.log($scope.text);
}, 1000);
}
};
});