如何在每次调用指令时创建一个唯一的作用域(AngularJS)

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

本文关键字:一个 唯一 AngularJS 作用域 创建 调用 指令      更新时间:2023-09-26

我正在创建一个带有'widgets'的页面。我已经创建了指令/控制器/工厂/模板文件,当每页只使用1个时,一切都很好,但是当我使用多个时,会出现问题。

我的指令:

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>

如果我将以下代码添加到主HTML文件

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

输出为:

widget_1

但是当我添加2个小部件时,例如:

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

输出为:

widget_2

widget_2

由于每次创建新的"小部件"时只有一个scope.widget被覆盖(我假设…)。


是否有一种方法来创建一个唯一的范围/var每次创建一个新的小部件?

使用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';
        }
    }
}])

为了更好地理解directivescope的概念:

请参考此链接:"http://www.undefinednull.com/2014/02/11/mastering-the-scope-of-a-directive-in-angularjs/"

相关文章: