How to set repeating item id in AngularJS?

I would like to do something like:

<div class='row' ng-repeat='row in _.range(0,12)'> <div id='{{row}}'></div> </div> 

but when in the controller I try:

 function SetterForCatanCtrl($scope) { $scope._ = _; try { var tile = document.getElementById('5'); tile.style.backgroundImage = "url('aoeu.png')"; } catch (e) { alert(e) } } 

getElementById returns null, so how can an element identifier be specified using AngularJS variables?

+8
angularjs
source share
1 answer

The SetterForCatanCtrl function SetterForCatanCtrl runs once when angular encounters the ngController directive when it loads your application. When this happens, the element you want to get from the DOM does not exist yet.

Performing DOM manipulations with the controller is not good practice ; directives can solve the problem you are facing. Your use case can be solved with CSS and just switch the classes, but I think you want to do more than just set the background image.

DOM processing from the controller

You do not request custom directives, so a quick fix can be done using the ngClick directive and call a method that can switch images

HTML example

 <div ng-controller='ctrl'> <div class='row' ng-repeat='row in _.range(0,12)'> <div id='{{row}}' ng-click="click($index)"> <button>{{row}}</button> </div> </div> </div> 

And js

 var App = angular.module('app', []); App.run(function($rootScope) { $rootScope._ = _; }); App.controller('ctrl', function($scope){ $scope.click = function(idx){ var elem = document.getElementById(idx); console.log('clicked row', idx, elem); }; ​}); ​ 

So, when the button is pressed, you will get the identifier and use it to get the element from the DOM. But let me repeat: for this use case, the directive is the best choice.

JSFiddle: http://jsfiddle.net/jaimem/3Cm2Y/

pd: if you are loading jQuery, you can use angular.element(<selector>) to select elements from the DOM.


edit: add sample directive

DOM processing from directive

Using the directive is simpler, since you can simply bind the event to the element to which the directive is applied to

HTML

 <h1>Directive</h1> <div class='row' ng-repeat='row in _.range(0,12)'> <div id='{{row}}' my-directive> <button>{{row}}</button> </div> </div> 

Js

 App.directive('myDirective', function(){ return function(scope, element, attr){ element.bind('click', function(){ console.log('clicked element: ', element, element.html()); }); }; }); 

http://jsfiddle.net/jaimem/3Cm2Y/1/

+13
source share

All Articles