我有一个指令,当用户悬停在新闻上时,使新闻项具有类似usatoday.com的效果。我刚接触angularjs :D
指令:
app.directive('hotEvent', ['$rootScope', function ($rootScope) {
return {
restrict: 'EA',
templateUrl: '/App/Main/views/home/events.html',
link: function (scope, iElement, attrs) {
//attrs references any attributes on the directive element in html
var dathumb = $(iElement).find('.da-thumbs > li a');
//$(function () {
dathumb.each(function () {
$(this).hoverdir();
});
//});
}
};
}]);查看: /App/Main/views/home/events.html
<ul class="row da-thumbs">
<li ng-repeat="news in featuredEvents">
<a href="/">
<img src="abc.jpg" /> >> no effect ???
<div>
<h4>aaa</h4>
<p>
bbb
</p>
</div>
</a>
</li>
<li>
<a href="/">
<img src="abc.jpg" /> >> show effect
<div>
<h4>bbb</h4>
<p>
ccc
</p>
</div>
</a>
</li>
</ul>在Home.html上:(已经绑定了控制器)
<div hot-event></div>当我不绑定控制器<li ng-repeat="news in featuredEvents">中的数据时,它就会起作用,现在效果就是没有表现出来。Console.log显示0错误。
更新:我最终使用document ready
app.directive('hotEvent', function () {
return {
restrict: 'EA',
templateUrl: '/App/Main/views/home/events.html',
link: function ($scope, iElement, attrs) {
angular.element(document).ready(function () {
var dathumb = $(iElement).find('.da-thumbs > li a');
dathumb.each(function () {
$(this).hoverdir();
});
});
}
}
});发布于 2014-10-31 16:52:16
如果你调试你的代码,你会发现你的指令没有找到任何元素。
这是因为当模板加载时,指令链接函数被调用,但是ng repeat没有时间自己填充它(它从空开始),因为它没有地方可以找到。
一个简单的解决方法是在angular 0函数中使用jquery find方法,或者在执行jquery find的函数上使用$scope.evalAsync (它需要angular 1.3)。
但最好的解决方案是修复代码,使其实际上不需要jquery。
附注:当你看到自己在指令中使用选择器时,你通常在angular中做了错误的事情(注意:通常),请参考这个"Thinking in AngularJS" if I have a jQuery background?很棒的问题和答案。请注意,他实际上是说,当您第一次学习angular时,根本不要使用jquery :)
https://stackoverflow.com/questions/26670336
复制相似问题