加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:37:52 所属栏目:安全 来源:网络整理
导读:这是我的指令代码: // Generated by CoffeeScript 1.6.3(function() { var autumnDirectives; autumnDirectives = angular.module('autumnDirectives',[]); autumnDirectives.directive('timeline',function() { return { scope: { timeline: '=' },templat
这是我的指令代码:

// 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检查工具的孩子,我就能找到.item.

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

否则一切正常

谢谢

注意:我能够使用.timeline类找到层次结构中的第一个div,但在更深层次上没有任何内容

解决方法

你应该在$timeout内运行它:

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

会发生什么是ngRepeat使用回调注册$watchCollection.
当$digest发生时,该回调克隆DOM元素.
在$digest之前没有DOM元素可用.
在$digest之后运行$timeout,因此我们可以安全地引用DOM元素.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读