Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set repeated element id in AngularJS?

Tags:

angularjs

I'd 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's id be set using AngularJS variables?

like image 243
Noel Yap Avatar asked Dec 05 '12 07:12

Noel Yap


1 Answers

The function SetterForCatanCtrl is run only once, when angular encounters a ngController directive while it bootstraps your app. When this happens the element you want to access from the DOM doesn't exist yet.

Doing DOM manipulation from a controller is not a good practice, directives are can solve the kind of problem you are facing. Your use case can be solved with CSS and just switching classes but I guess you want to do more than just setting a background image.

DOM manipulation from a controller

You are not asking for custom directives, so a quick solution could done using the ngClick directive and call a method that can switch images

Example HTML

<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 a button is clicked you will get an id and use it to get an element from the DOM. But let me repeat, a for this use case a directive is a better choice.

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

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


edit: adding directive example

DOM manipulation from a directive

Using a directive is simpler, since you can just bind an event to the element 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/

like image 68
jaime Avatar answered Oct 13 '22 23:10

jaime