AngularJS supports .attr(), .removeAttr() jQuery functionality. Here in below examples we can see how to set attribute and remove attribute of an element.
Angular2 : If you are looking for Angular2 solution, please click here

Read or Assign value to attribute :

By using expressions, attribute values can be changed. Observe below code
....
<input ng-model="atribut"/>
....
<div myattr="{{atribut}}" id="divID">
  Attribute DIV <b>{{atribut}}</b>
</div>
<script>
function myCtrl($scope) {
    $scope.atribut="val 1";
}
</script>

Steps to read attribute value of an elemnt :

  1. Get angular element of html element
  2. Use .attr('attribute name') method to read the attribute value
var myEl = angular.element( document.querySelector( '#divID' ) );
alert(myEl.attr('myattr'));

Steps to set attribute value of an element :

  1. Get angular element
  2. Use .attr('attribute name', 'attribute value') method to set the attribute value
var myEl = angular.element( document.querySelector( '#divID' ) );
myEl.attr('myattr',"attr val");

Steps to remove attribute of an element :

  1. Get angular element
  2. Use .attr('attribute name', 'attribute value') method to set the attribute value
var myEl = angular.element( document.querySelector( '#divID' ) );
myEl.removeAttr('myattr');

6 comments:

  1. I need to set focus on a textbox when a hyperlink is clicked. I tried angular.element("#id").focus(), and $("#id").focus(), but nothing works. Is there an easier way to handle focus in angular?

    ReplyDelete
    Replies
    1. will that hyperlink redirects to new page or stays in same page ( with only # tag change) ?

      Delete
  2. does setting attribute work with angular version 1.5.0

    ReplyDelete
  3. what if the attribute is an object?

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts