Multiple ng-bind in the same directive

1.7k views Asked by At

I'm trying to use multiple ng-bind instead of {{}} in a directive, but with no luck.

<my-directive att1="age" att2="22"></my-directive>

angular
    .module("app",[])
    .directive('myDirective', myDirective);

function myDirective() {
    return {
        restrict: 'E',
        scope: {
            att1: '@',
            att2: '@'
        },
        template: '<div class="ng-bind: att1;" ng-bind="att2"></div>'
    }
}

No problem in case there's only one ng-bind. In case I have more than one, as in this case, I read somewhere about the notation I'm using "ng-bind: att;" but it's not working.

Also, I wonder if I'd really would need it. Apparently using ng-bind avoid the problem of the double bracket flashing in the screen before the data is loaded, which in this case it's not really important as I'm using the value as a class attribute and thus is not being displayed in the screen. On the other hand it's supposed to be more efficient using ng-bind.

Any ideas? I've seen a couple questions here in stackoverflow regarding this but none of them seem to resolve the matter.

1

There are 1 answers

2
23tux On

You only can have one ng-bind per attribute. The value of ng-bind is written as the content of your div tag. When you have multiple ng-binds they would overwrite each other, so this is not possible.

However, if you want to set a class, have a look at the ngClass directive here https://docs.angularjs.org/api/ng/directive/ngClass. Your template could look sth like this:

template: '<div ng-class="att1" ng-bind="att2"></div>'

This would set the content of att1 into the class="..." attribute of your div and the content of att2 as the content of your div. The rendered output could be

<div class="your-att1-value">your att2 value</div>

If you want more than one ng-bind you could insert a seperat tag for each ng-bind like this:

template: '<div><span ng-bind="att1"></span><span ng-bind="att2"></span></div>'