Kevin Dai
Kevin Dai

Reputation: 77

What iElement represents in link function in AngularJS?

Html:

<tr ng-repeat="model in ModelList">
  <td>
      <div my-directive name="Sub_{{$index}}">
      </div>
  </td>               
</tr>     

Javascript Snippet:

.directive("myDirective", function(){

    return function (scope, iElement, attrs) {

                    //current name:  Sub_{{$index}}
                    console.log("current name:  " + iElement.attr("name"));

                    //outerHTML: "<div my-directive="" name="Sub_2"></div>"
                    console.dir(iElement);

           };
});

My question is, why it return unresolved name( Sub_{{$index}} ) when i call iElement.attr("name"), and return resolved html( name="Sub_2" ) when i call console.dir(iElement)?

Here are outputs:

1.enter image description here
2.enter image description here

What exactly is iElement behind the scene?

Upvotes: 1

Views: 733

Answers (2)

georgeawg
georgeawg

Reputation: 48968

What exactly is iElement behind the scene?

It is the raw DOM element of the directive wrapped in a jqLite wrapper. For more information on jqLite and its methods see the AngularJS angular.element API Reference -- jqLite

why it return unresolved name( Sub_{{$index}} ) when i call iElement.attr("name")

You are seeing the raw attribute before the directive compiler applies $interpolate to it.

and return resolved html( name="Sub_2" ) when i call console.dir(iElement)?

When you use console.dir(iElement) the console shows the object reference at its present value (not past value) which is after the attribute has been interpolated.

More information

For more information on the scope methods such as $eval, $watch, etc. see the AngularJS $rootScope.scope API Reference.

For more information on the attrs methods such as $observe, the AngularJS $compile Directive Attributes API Reference.

Upvotes: 1

mcgraphix
mcgraphix

Reputation: 2733

Perhaps it is just a timing issue related to when those bindings get resolved. Instead of trying to get the attribute off the element, have you tried just accessing it from the attrs object that is passed into your link function?

attrs.name

You get the added benefit of angular normalizing the attribute names for you. See https://docs.angularjs.org/api/ng/type/$compile.directive.Attributes

If you are accessing it just as an attribute, you may need to observe it for changes if you need to account for values that could change after the initial render.

scope.$observe(attrs, "name", function(newVal) {
   //do something with the new value
});

Upvotes: 0

Related Questions