我想要訪問控制器功能中指令的屬性。但是,當我訪問它時,它是不確定的。我注意到,如果我做了一個簡單的計時器,它的作品。有沒有一種方法可以在指令之後執行代碼,並且它的作用域已準備好並設置爲使用?AngularJS指令屬性訪問控制器
我用它做了一個小提琴。確保您的控制檯處於打開狀態。 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);
}
};
});
燁,爲我工作:)感謝的人 – PCoelho 2013-03-01 06:06:52
這將失敗掉毛。因爲'attrs.text'是未知的。 – 2016-10-24 12:36:38
@DougChamberlain你可以使用JSDoc來解決這個問題。像''@param {string} attrs.text''應該可以解決你的問題。 – 2017-07-24 13:10:40