0

I want to grab an element by his class with JQuery, but for some reason that's not working. The length of the JQuery object is 0, and that's happening only, if I want the class that is inside the element with 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

t0mppa
  • 3,983
  • 5
  • 37
  • 48
Bazinga
  • 10,716
  • 6
  • 38
  • 63

4 Answers4

1

It's returning length of 0 cause the divs aren't rendered onto the DOM yet. $timeout is one workaround, but I would use:

angular.element(document).ready(function () {
    console.log($('.user').length)
});
elzi
  • 5,442
  • 7
  • 37
  • 61
0

Your directive markup is primitive. You should use directives like shown below and you wont have to use a $timeout hack. The link() function is used to manipulate the DOM after it has loaded.

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

One way to accomplish this is to wrap your query in a $timeout which will cause the query to run on the next digest loop:

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

        console.log('Im here');

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


      }
    })
sma
  • 9,449
  • 8
  • 51
  • 80
-1

Use timeout

.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

Simon H
  • 20,332
  • 14
  • 71
  • 128