How to get values resolved in template without double curly brackets

681 views Asked by At

I am using directive and template. My template is as follows

<div>
    <a data-my-dir="item" data-attr1="true"
        data-attr2="{{itemParentId}}"
        data-attr3="{{item.id}}">
    </a>
</div>

Here due to curly braces watches are added and it is affecting my performance. I don't want watches as I am not going to modify attr2 or attr3. I want to directly resolved value here only.

We can use bindonce directive where we don't want watches where we can use bo-text="xyz" instead, but here I want to pass values as attr to my custom directive.

Inside my directive's link function I am binding click event with element as follows

link: function (scope, element, attrs) {
    element.bind('click', function (event) {
        var myAttr1 = attrs.attr1;
        var myAttr2 = attrs.attr2;
    }
}

So due to those watches in template on attr1 and attr2 I am getting these values resolved in click event.

What are the alternatives?

2

There are 2 answers

3
Jossef Harush Kadouri On BEST ANSWER

One time Binding

Seems like a good use case for one time binding (if you are using angular 1.3+)

<div>
    <a data-my-dir="item" 
        data-attr1="true"
        data-attr2="{{::itemParentId}}"
        data-attr3="{{::item.id}}">
    </a>
</div>

the directive would look like

angular.module('app', [])
  .directive("myDir", function() {
    return {
      restrict: "A",
      scope: {
         "attr1": "@",
         "attr2": "@",
         "attr3": "@",
      },
      template: '<span> {{attr1}} {{attr2}} {{attr3}}</span>'
    };
  })

Demo

http://plnkr.co/edit/GJCZmb9CTknZZbcRHN7s?p=preview

1
Pankaj Parkar On

You could use data-attr2="itemParentId" directly but for that you need to use = as currently you are using @ option of directive.

app.directive('myDir', function(){
    return {
       scope: {
           dataAttr1: '=', //or '=dataAttr1'
           dataAttr2: '=' //or '=dataAttr2'
       },
       link: function(scope, element, attrs){
           console.log(scope.dataAttr1);
           console.log(scope.dataAttr2);
       }
    }
})