chu*_*ubs 22 javascript angularjs angularjs-directive
我有一个简单的指令,其中模板在其中使用ng-repeat.我需要运行一些代码来针对ng-repeat指令创建的一些元素实例化一个jquery组件.问题是如果我把这段代码放在链接函数中.ng-repeat尚未构建这些元素,因此没有实例化.
App.directive('myDirective', ['$compile', '$timeout', function($compile, $timeout) {
return {
scope: {
domains: '='
},
templateUrl: '/app/partials/my_directive.html',
link: function($scope, element, attributes) {
element.find('.standard-help').tooltip('destroy');
element.find('.standard-help').tooltip({placement: 'top', trigger: 'click hover focus'});
}
};
}
Run Code Online (Sandbox Code Playgroud)
模板看起来如下所示.我想附上
<ul class="media-list domainList">
<li class="media" style="position:relative;" ng-repeat="domain in domains">
<a class="domainHeader" href="javascript://">
<span class="domainHeader">{{domain.tag}}</span>
</a>
<div class="media-body" style="margin-left: 52px;">
<ul class="standardsList">
<li ng-class="{ standardDisplayed: lessonLayout == 'standards' }" ng-hide="standard.lessons.length == 0" ng-repeat="standard in domain.standards">
<a href="javascript://" title="{{standard.description}}" ng-show="lessonLayout == 'standards'" class="standard-help pull-right"><i class="icon-question-sign"></i></a>
<h6 ng-show="lessonLayout == 'standards'">{{standard.tag}}</h6>
<ul class="lessonsList">
<li ng-class="{ lesson: true }" ng-repeat="lesson in standard.lessons" ng-click="onLessonSelected(lesson)">
<i class="icon-lock lesson-locked"></i>
<div>{{lesson.title}}</div>
</li>
</ul>
</li>
</ul>
</div>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
我尝试使用$ watch()和$ observe()在域更改时注册回调,然后实例化工具提示代码.但是,我似乎无法在合适的时间给我打电话.我缺少什么想法?
chu*_*ubs 23
我发现如果创建了另一个指令,我将其添加到创建ng-repeat的元素中,则会通知重复创建的每个元素.然后我可以简单地$发出一个父指令可以监听的事件.此时它可以执行与那里重复元素的链接.这非常适用于dom中的多个ng-repeats,因为我可以通过它们传递给new指令的事件类型来区分它们.
这是我的指示:
App.directive("onRepeatDone", function() {
return {
restrict: 'A',
link: function($scope, element, attributes ) {
$scope.$emit(attributes["onRepeatDone"] || "repeat_done", element);
}
}
});
Run Code Online (Sandbox Code Playgroud)
以下是模板中新指令的用法:
<ul>
<li on-repeat-done="domain_done" ng-repeat="domain in domains">...</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
然后在父指令中我可以执行以下操作:
link: function( $scope, element, attributes ) {
$scope.$on('domain_done', function( domainElement ) {
domainElement.find('.someElementInsideARepeatedElement').click(...);
} );
}
Run Code Online (Sandbox Code Playgroud)
Ye *_*Liu 10
$watch 应该能够实现你想做的事:
link: function(scope, elem, attrs) {
var init = function() {
// your initialization code
};
var ulElem = elem.children()[0]; // ul element
var unreg = scope.$watch(function() {
return ulElem.children.length === scope.domains.length; // check if all "li" are generated
}, function() {
// at this point, the ul is rendered
init();
unreg(); // unregister the watcher for performance, since the init function only need to be called once
});
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个插件来演示这个解决方案.
| 归档时间: |
|
| 查看次数: |
21743 次 |
| 最近记录: |