Jeffrey Roosendaal
Jeffrey Roosendaal

Reputation: 7157

How to create a unique scope each time a directive is called (AngularJS)

I'm creating a page with 'widgets'. I've created directive/controller/factory/template files, and everything is working fine when using only 1 per page, but there's a problem when I use multiple.

My directive:

app.directive('widget', ['widgets', function(widgets){
    return {
        restrict: 'E',
        link: function(scope, element, attrs) { 
            
            // Send attributes to template
            scope.widget = {
                id      : attrs.id,
                type    : attrs.type,
                view    : attrs.view
            }
            
        },
        templateUrl: function(elem, attrs) {
            return false || 'tpl/widgets/' + attrs.type + 's.html';
        }
    }
}])

My templateUrl file:

<div ng-controller="Widgets">
    {{widget.id}}
</div>

If I add the following code to my main HTML file

<widget id="widget_1" type="table" view="basic"></widget>

The output is:

widget_1

But when I add 2 widgets, for example:

<widget id="widget_1" type="table" view="basic" views="basic"></widget>
<widget id="widget_2" type="table" view="basic" views="basic"></widget>

The output is:

widget_2

widget_2

Since there's only one scope.widget which is overwritten each time a new 'widget' is created (I assume..).


Is there a way to create a unique scope/var each time a new widget is created?

Upvotes: 0

Views: 927

Answers (1)

sahil gupta
sahil gupta

Reputation: 2349

Use isolate scope

app.directive('widget', ['widgets', function(widgets){
    return {
        restrict: 'E',
        scope:{},
        link: function(scope, element, attrs) { 

            // Send attributes to template
            scope.widget = {
                id      : attrs.id,
                type    : attrs.type,
                view    : attrs.view
            }

        },
        templateUrl: function(elem, attrs) {
            return false || 'tpl/widgets/' + attrs.type + 's.html';
        }
    }
}])

To better understand concept of scope in directive:

Please refer to this link : "http://www.undefinednull.com/2014/02/11/mastering-the-scope-of-a-directive-in-angularjs/"

Upvotes: 3

Related Questions