【问题标题】:Access compiled ng-repeat children elements in link function of a custom directive在自定义指令的链接函数中访问已编译的 ng-repeat 子元素
【发布时间】:2015-04-03 14:30:48
【问题描述】:

我想在自定义指令的链接函数中获取父容器的 ng-repeat 子元素。我希望 link 函数中传递的 element 参数应该可以完成这项工作。像这样的

element.children() // gets all children elements

相反,我有文本节点 <!-- ngRepeat: course in courses -->

这是我的指令元素:

<course-list courses="courses"></course-list>

这里是指令实现

angular.module('pgCoursesList', [])
.directive('coursesList', [
    function() {
        return {
            restrict: 'E', 
            scope: {
                courses: '=',
                buttonText: '@'
            },
            template: '<div class="courseslist-container">' +
                    '<div ng-repeat="course in courses" class="media">' +
                        '<div class="media-left"><a class="img-thumb-64 blank-thumb-img" href="#">64x64</a></div>' +
                        '<div class="media-body clearfix">' +
                            '<h4 class="media-heading pull-left">{{course.name}}</h4>' +
                        '</div>' +
                        '<div class="media-left"><button btn-style="btn-success"></button></div>' +
                        '<hr />' +
                    '</div>' +
                '</div>',
            replace: true,
            link: function(scope, elem) {
                // elem.children()   
            }
        };
    }
]);

【问题讨论】:

  • 你能在小提琴中分享你的代码吗?

标签: javascript angularjs angularjs-directive frontend


【解决方案1】:

这是一种 hack,但您可以使用 ng-init 来实现。 我们可以通过检查 $last 内的 ng-repeat 来跟踪最后一个元素是否在 DOM 上呈现。只需要在 ng-repeat div 中添加ng-init="$last &amp;&amp; domRendered()"

代码更改

template: '<div class="courseslist-container">' +
 '<div ng-repeat="course in courses" class="media">' +
 '<div class="media-left"><a class="img-thumb-64 blank-thumb-img" href="#" ng-init="$last && domRendered()">64x64</a></div>' +
  '<div class="media-body clearfix">' +
   '<h4 class="media-heading pull-left">{{course.name}}</h4>' +
  '</div>' +
  '<div class="media-left"><button btn-style="btn-success"></button></div>' +
  '<hr />' +
 '</div>' +
'</div>',
link: function(scope, element){
  scope.domRendered = function(){
     element.children(); //you can get element children here
  };
 }

或者更多更好的方法你可以试试this链接。为此,您需要再添加一个指令。

希望这可以帮助你。 谢谢。

【讨论】:

  • @Stanislav Zaichenko 这对你有帮助吗?
猜你喜欢
  • 2017-07-29
  • 2013-07-26
  • 2016-11-14
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多