Search code examples
javascriptjqueryhtmlangularjsangularjs-ng-repeat

How to get a variable attribute of an HTML element?


I have a ng-repeat in which I have set an attribute like so:

<div ng-repeat="item in itemsList"
     stepType="{{item.stepType}}">
     {{item.itemValue}}
</div>

item.stepType can have values 'task' or 'action' I'm trying to get the attribute 'stepType' like so:

let stepType = el.getAttributeNode("stepType");
console.log(stepType.value);

The result i'm getting is:

{{item.stepType}}

But the expected result is task or action

I also tried to get the attribute using the function getAttribute() but the result is the same.

I also noticed that in the above code if i log the value of stepType instead of stepType.value, i get the object which looks like this stepType: 'task'

How can i get the expected value?


Solution

  • If the attribute name is normalized:

    <div ng-repeat="item in itemsList"
         step-type="{{item.stepType}}">
         {{item.itemValue}}
    </div>
    

    A custom AngularJS directive can $observe the attribute:

    app.directive("stepType", function() {
        return {
            link: postLink
        };
        function postLink(scope, elem, attrs) {
            attrs.$observe("stepType", function(value) {
                console.log(value);
            });
        }
    })
    

    The console will log changes to the interpolated value of the attribute.