我正在尝试访问控制器函数中指令的属性。然而,当我访问它时,它是未定义的。我注意到如果我做一个简单的计时器它就可以工作。有没有办法仅在指令及其范围准备好并设置为使用之后才执行代码?
我摆弄了它。确保您的控制台已打开。http://jsfiddle.net/paulocoelho/uKA2L/1/ 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);
}
};
});
有效的是,如果你设置
scope.text = $attrs.text;
在链接和控制器功能内部。这仅在最初有效,因为没有 2way 数据绑定。您可以使用$attrs.observe https://docs.angularjs.org/api/ng/type/%24compile.directive.Attributes though.
参见小提琴:http://jsfiddle.net/JohannesJo/nm3FL/2/ http://jsfiddle.net/JohannesJo/nm3FL/2/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)