4

我正在尝试使用 Jquery 插件在 AngularJS 指令中操作 DOM。

我不确定 AngularJs 是否使用完整版的 Jquery,尽管完整版脚本在头上,而 AngularJs 脚本在正文上,所以理论上 AngularJS 应该使用完整版。但是,指令内部的日志条目没有显示任何被选中的内容。虽然 Chrome 控制台中完全相同的语法会返回 ul 中的所有 lis。

这是HTML

<ul id="myUl"  class="gallery unstyled">
    <li class="galleryitem" ng-repeat="i in images">
        <a href="{{i.LargeImage.URL}}"><img ng-src="{{i.MediumImage.URL}}" /></a>
    </li>
</ul>

指示

.directive('gallery',function() {
    return {
        restrict : 'C',
        link : function postLink(scope, iElement, iAttrs) {
        console.log($(".gallery li"));
      }
    }
   }

PS:我才意识到

console.log($(".gallery"));

确实返回带有 li 的 ul 但不是

console.log($(".gallery li"));

这让我觉得完整版没有加载。

4

2 回答 2

5

jQuery is loaded, but when you call $('.gallery') in the linking function the ng-repeater expression has not been evaluated yet, so at that moment all those li elements are not in the DOM. Just to experiment, you can add a delay before calling the selector

setTimeout(function(){
  console.log($(".gallery li"));
}, 1000);

Then, you'll get all the li elements because you are querying the DOM after ng-repeater was evaluated. This is why running selecting the li nodes from the console works.

Before continuing, when it's said that angular uses jQuery when the library is loaded means that angular.element implements selectors and that references to elements inside directives have jQuery methods available. The recommendation is to manipulate the DOM in the context of the directive's element

iElement.find('li')    // instead of $('.gallery li')

Now, you might be wondering, then how do I modify the DOM? Well, it depends of what exactly are you trying to achieve. Since you want to manipulate the DOM after all the li have been rendered in the ngRepeater you might want to use a special directive checkLast that checks when the last item in the repeater is rendered by checking if $last is true

Here's a jsfiddle from someone in this google groups discussion.

Or you could $watch for some scope property to change.

于 2012-12-17T00:28:25.677 回答
0

对于那些像我一样寻找答案的人,试试这个

    .directive('gallery',function() {
        return {
            restrict : 'C',
            link : function postLink(scope, iElement, iAttrs) {
                iElement.ready(function(){
                    console.log($(".gallery li"));
                });        
            }
        }
    }

通过这种方式,您可以确保您的 iElement 已准备好进行 dom 操作

于 2014-06-18T20:58:44.963 回答