Batu.Khan
Batu.Khan

Reputation: 3065

Angular - How to use an attribute's value in a custom directive?

Super Angular rookie here.

Got a custom directive to create an element that will write a value of an attribute into a span :

myApp.directive("myDirective", function(){
    return {
        restrict : "E",
        template : "<span>{{ dirCtrl.dirText }}</span>",
        controller : function($attrs){
            this.dirText = $attrs.dirText;
        },  
        controllerAs : "dirCtrl"
    };
});

To test it if a write

<my-directive dir-text="Test 1 2 3"></my-directive>

Output is Test 1 2 3 as expected but if i use more than once

<my-directive dir-text="Test 1 2 3"></my-directive><br>
<my-directive dir-text="Test 4 5 6"></my-directive>

Output is

Test 4 5 6
Test 4 5 6

but i expect it to be

Test 1 2 3
Test 4 5 6

So, what do i do wrong?

FIDDLE

Upvotes: 0

Views: 30

Answers (1)

PSL
PSL

Reputation: 123739

You would need to use scope:true, (create child scope) or scope:{},(create isolated scope) option in your directive, otherwise bothe the directive instances use the same scope and setting dirCtrl.dirText is also on the same scope so last one overwrites any other previous instance set values. Using a childscope or isolated scope creates a scope for that directive itself which is more appropriate as well in your case. Whenever you set a property on the scope from a directive it is always advisable to create a scope for the directive (unless that is really the intention), because often you don't want to pollute the current scope where the directive is in.

.directive("myDirective", function(){
    return {
        restrict : "E",
        scope:true,
        template : "<span>{{ dirCtrl.dirText }}</span>",
        controller : function($attrs){
            this.dirText = $attrs.dirText;
        },
        controllerAs : "dirCtrl"
    };
});

Fiddle

Upvotes: 2

Related Questions