vlio20
vlio20

Reputation: 9295

Angular with {{}} directive attribute

Is there any way to pass {{string}} to directive which gets this attribute from $attrs (not $scope)?

Here is some code:

controller:

...
scope.someId = "someId";
...

HTML:

<my-dir id="{{someId}}"></my-dir>

Directive

app.directive('myDir', function() {
   return {
      controller: function($attrs){
         console.log($attrs.id) //output: {{someId}}
      }
   }
})

What I want is that the output would be someId and not {{someId}}.

Upvotes: 0

Views: 62

Answers (2)

Hazarapet Tunanyan
Hazarapet Tunanyan

Reputation: 2865

Here is a good and more professional way to do it.In angularjs there is an idea about scope field type:

There are 3 types of it.

1) string @

2) functional &

3) biDirectional =

This style is better.This link can help you.

https://docs.angularjs.org/api/ng/service/$compile#directive-definition-object

Upvotes: 0

Vinay K
Vinay K

Reputation: 5572

You will not be able to access the value from $attrs till the initial digest cycle is triggered. Once the digest cycle is triggered, you will be able to access it from the $attrs.

app.directive('myDir', function() {
   return {
      controller: function($attrs){
         console.log($attrs.id) //output: {{someId}}
         $attrs.$observe('id', function (newVal, oldVal) {
             console.log(newVal, oldVal); // here you will be able to access the evaluated value. 
         });
      }
   }
})

Upvotes: 1

Related Questions