Angular不能在ng-repeat div中逐个获取元素

时间:2014-11-18 19:58:02

标签: javascript jquery angularjs

我想通过他的类使用JQuery获取一个元素,但由于某种原因,它不起作用。 JQuery对象的长度为0,如果我想要使用ng-repeat的元素内部的类,则只发生这种情况。

的index.html

<body ng-controller="MainCtrl">
  <div user>
    <div ng-repeat="user in users" class="user">
      <p>{{user.name}}</p>
    </div>
  </div>
</body>

app.js

app.controller('MainCtrl', function($scope) {
  $scope.users = [{name: 'name1'}, {name: 'name2'}];
});

.directive('user', function() {
  return function(scope, ele) {

    console.log('Im here');

    console.log($('.user')); // this is not working the length is 0
  }
})

plunker:http://plnkr.co/edit/MYYoam0XFUrKIB4f2zOT

4 个答案:

答案 0 :(得分:0)

它的返回长度为0会导致div尚未呈现在DOM上。 $timeout是一种解决方法,但我会使用:

angular.element(document).ready(function () {
    console.log($('.user').length)
});

答案 1 :(得分:0)

您的指令标记是原始的。你应该使用如下所示的指令,你不必使用$ timeout hack。 link()函数用于在加载DOM之后对其进行操作。

angular.module('project').directive('user', [
    function () {
        return {
            templateUrl: 'views/DirectiveSample.html',
            restrict: 'A',
            scope: {
                users: '='
            },
            link: function postLink(scope, element, attrs) {
                console.log($('.user'));
            }
        };
    }
]);

答案 2 :(得分:-1)

实现此目的的一种方法是将查询包装在$timeout中,这将导致查询在下一个摘要循环上运行:

.directive('user', function($timeout) {
      return function(scope, ele) {

        console.log('Im here');

        $timeout(function () {
             console.log($('.user')); 
        });


      }
    })

答案 3 :(得分:-1)

使用超时

.directive('user', function($timeout) {
  return function(scope, ele) {

    console.log('Im here');

    $timeout(function() {
      console.log(ele[0].offsetHeight); 
      },0);// this is not working the length is 0
  }
})

http://plnkr.co/edit/cCM8q1mVABzZSBccufvC?p=preview