vedant sali
vedant sali

Reputation: 80

get element by Id and addClass in angularjs

m trying to get a element by its Id in angularJs and then add a class to it. I have used "ng-attr-id" to assign id to my element and now m not able to addClass to it.

html:

<div ng-attr-id= {{id}} >Text</div>
<button ng-click="action">action</button>

script:

  $scope.id="name";

  $scope.action=function(){
  angular.element($document[0].getElementById("name")).addClass("align");
  }

the plunkr : http://plnkr.co/edit/VjORCl5xoHQZbzBG6HDp?p=preview

PS :Any solution other than using ng-class will be more appreciated. I dont need that based on my current problem

Upvotes: 0

Views: 34924

Answers (3)

TobyGWilliams
TobyGWilliams

Reputation: 631

Can I suggest that you use the ng-class function to manage your class on the elements?

<div ng-class="{align: clicked}">Text</div>
<button ng-click="clicked=!clicked">action</button>
<script>
    var app = angular.module('myApp', [])
    app.controller('Ctrl', function($scope){
        $scope.id="name"
        $scope.clicked=false
    })
</script>

plunker: http://plnkr.co/edit/GIYbaDnpAugF1ll3fE5C?p=preview

ng-class gets evaluated and where the variables are truthy, those classes get added to the element automatically.

Upvotes: 1

jnthnjns
jnthnjns

Reputation: 8925

By Making a couple minor changes, your code will work. Although my preference is generally to use ng-class as others have mentioned above.

Controller.js

var app = angular.module('myApp',[]);

app.controller('Ctrl', function($scope) {
    $scope.id="name";

    $scope.action=function(){
      // Angular Element can select by id directly but you just need to add the #
      angular.element('#name').addClass("align");
    };
});

index.html

<!-- id can simply be set but you need the quotes -->
<div id='{{id}}'>Text</div>
<!-- Missing parenthesis on function call -->
<button ng-click="action()">action</button>

Check out the plunker

Upvotes: 4

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

Using ng-class would make more sense here rather than using .addClass method

<div ng-attr-id= {{id}} ng-class="{align: align}">Text</div>
<button ng-click="align=true">action</button>

Upvotes: 0

Related Questions