Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs - Access to DOM element inside ng-repeat

I have the next template:

<div ng-repeat="friend in friends | filter:filterFriendsHandler">
   {{friend.name}}
</div>

and in my controller i have:

$scope.filterFriendsHandler = function(friend){
    //HERE I WANT TO ACCESS TO FRIEND DOM ELEMENT; to do something like this: 
    //$(friendElement).text('foo');
}

Thanks

like image 920
Zzarcon Avatar asked Mar 14 '13 17:03

Zzarcon


1 Answers

I'm going to answer the specific question here, yes I understand this isn't the "angular" way of doing things. If you want to do things the "correct" way, then don't do this, use a directive. There, disclaimers aside, here's how to do it:

Basically, what you want to do is give the DOM element an ID based on the $index or a unique value in your ng-repeat object. Here, I'll just use $index.

<div ng-repeat="friend in friends" id="friend_{{$index}}" ng-bind-html="doSomethingBadToTheDom('friend_' + $index)">
   {{friend.title}}
</div>

Then, inside your controller, just query the DOM for the element with that ID:

$scope.doSomethingBadToTheDom = function(ele_id) {
    var element = document.getElementById(ele_id);
    element.innerHTML = "I'm abusing angular";
} 

We're using ng-bind-html here because the DOM element will exist when your controller function executes, in the case of something like ng-init, it won't.

Again, this goes against everything angular stands for, so if you're trying to follow angular best practices, don't do this.

I've run into situations where the technique is useful though, especially when dealing with non-angular libraries, or those times when the "angular way" is more trouble than it's worth.

like image 130
Clayton Gulick Avatar answered Sep 16 '22 14:09

Clayton Gulick