gpt4 book ai didi

javascript - AngularJS 指令属性从 Controller 访问

转载 作者:IT王子 更新时间:2023-10-29 03:11:13 27 4
gpt4 key购买 nike

我正在尝试访问 Controller 函数中指令的属性。但是,当我访问它时,它是未定义的。我注意到,如果我做一个简单的计时器,它就会起作用。有没有一种方法可以仅在指令及其作用域准备就绪并设置为可以使用后才执行代码?

我用它做了一个 fiddle 。确保您的控制台已打开。 http://jsfiddle.net/paulocoelho/uKA2L/1/

这是我在 fiddle 中使用的代码:

<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;

在链接和 Controller 函数中。这只会在最初起作用,因为没有 2way- 数据绑定(bind)。您可以使用 $attrs.observe虽然。

参见 fiddle :http://jsfiddle.net/JohannesJo/nm3FL/2/

关于javascript - AngularJS 指令属性从 Controller 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15151116/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com