jQuery没有找到AngularJS在指令中创建的元素

时间:2014-03-31 16:24:28

标签: jquery angularjs angularjs-directive

使用两个几乎相同的场景,我有两个不同的值:

第一种情况是:

<ul id="test1">
   <li>Test 1</li>
   <li>Test 2</li>
   <li>Test 3</li>
</ul>

第二种情况是:

<ul id="test2">
    <li ng-repeat="item in items">{{item}}</li>
</ul>

在AngularJS指令中,我想发现<li>元素中的<ul>元素。

...
link: function(scope, elem, attrs) {

    var firstLength = $("#test1 li").length; // it gives me 3.
    var secondLength = $("#test2 li").length; // it gives me nothing, 0.
}

为什么,在第二种情况下,我没有<li>元素,即使它们是由AngularJS生成的?谢谢!

2 个答案:

答案 0 :(得分:0)

我试图通过链接方法获得的内容正在执行 BEFORE AngularJS填充<li>数据。所以,它不会正常工作。谢谢你的所有答案!

答案 1 :(得分:0)

虽然海报很满意知道为什么会这样,但我想我应该添加自己的解决方案来解决这个问题以防其他人遇到这个问题。您可以通过观察用于生成元素的对象来轻松解决问题。

link: function($scope, $element, $attrs) {
  var initialized = false;

  $scope.$watch('items', function(newValue, oldValue) {
    if (initialized === false) {
      initialized = true;
      //do some stuff
      //i.e. do something with all items or unbind the watch

      return;
    }

    //do some other stuff if it's not the initialization run through
    //i.e. update just the changed item
  }, true);
}