gpt4 book ai didi

angularjs - 在链接函数中找不到指令 templateUrl 中的元素

转载 作者:行者123 更新时间:2023-12-04 19:07:20 26 4
gpt4 key购买 nike

这是我的指令代码:

// Generated by CoffeeScript 1.6.3
(function() {
var autumnDirectives;

autumnDirectives = angular.module('autumnDirectives', []);

autumnDirectives.directive('timeline', function() {
return {
scope: {
timeline: '='
},
templateUrl: 'partials/timeline/_timeline.html',
controller: function($scope, $element, $attrs) {
return console.log($scope.timeline);
},
link: function(scope, el, attrs) {
console.log(el);
return console.log(el.find(".item"));
}
};
});

}).call(this);

我的模板:
<div class="timeline clearfix">
<div class="item" ng-repeat="item in timeline">
<div class="row">
<div class="content">{{ item.content }}</div>
</div>

<div class="row">
<div class="connect_line"></div><div class="connect_line"></div>
</div>
</div>
</div>

出于某种原因,jqlite find 不会返回 item 元素(长度为 0)-或任何与此相关的元素。如果我在链接函数中附加一个元素,那么我就可以找到它,否则就不行。

当我登录 el 时,它会返回正确的元素,如果我使用 chromes 检查工具冒险进入 child ,我可以找到 .item。

我认为一旦模板准备好就调用该链接?这里出了什么问题,还是我不明白什么?

否则一切正常

谢谢

注意:我可以使用 .timeline 找到层次结构中的第一个 div。类,但没有更深层次的

最佳答案

你应该在 $timeout 里面运行它:

$timeout(function(){
console.log(el.find(".item"));
})

发生的事情是 ngRepeat注册一个带有回调的 $watchCollection。
当 $digest 发生时,该回调会克隆 DOM 元素。
在此之前 $digest 没有可用的 DOM 元素。
$timeout 在 $digest 之后运行,因此我们可以安全地引用 DOM 元素。

我做了一个plunker来检查元素何时加载到DOM: http://plnkr.co/edit/X8PuOQhhbQB3Gv657R35?p=preview

关于angularjs - 在链接函数中找不到指令 templateUrl 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21284595/

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