AngularJS指令访问相同的范围对象 - 避免覆盖

时间:2014-08-15 12:07:41

标签: javascript angularjs angularjs-directive

我试图将一个角度对象包装成一个模板,然后我可以通过使用一个指令来实例化它。在这种情况下,每个指令都是一种小部件。

问题来自于我正在编写的指令基于相同的类型,因此在实例化指令时,我会在全局范围内跟踪窗口小部件对象。我有以下几点:

.directive('lineChart', ['$interval', '$compile', 'widgetDataService',
    return {
            restrict: 'E',
            scope: false,
            templateUrl: 'templates/lineChart.html',
            link: function(scope, elm, attrs) {
                var obj = {
                    guid: attrs['guid'],
                    datasource: undefined
                }

                scope.widgets.push(obj)
...

然后在我可以做的模板中:

...
k-data-source="widgets[{{index}}].datasource"
...

这里的想法是随后使用该指令将导致顺序初始化模板 - 因此每个模板将获得其各自的索引。然而,这不起作用。如果我多次使用指令,则所有实例化模板都会获得最后一个索引,这可能意味着angular正在分离不同阶段的实例。

有没有办法使用全局对象来跟踪指令的底层对象,但仍然允许它们在运行时传入不同的索引?

1 个答案:

答案 0 :(得分:1)

您可以在指令的工厂函数中定义和设置变量(因为它只被调用一次),然后在链接阶段递增它:

.directive('lineChart', ['$interval', '$compile', 'widgetDataService',
  function($interval, $compile, widgetDataService) {
    var index = 0;  //initialize index
    return {
        restrict: 'E',
        scope: true,
        templateUrl: 'templates/lineChart.html',
        link: function(scope, elm, attrs) {
            var currentIndex = index++;  //increment on linking
            scope.index = currentIndex;
            var obj = {
                guid: attrs['guid'],
                datasource: undefined
            }

            scope.$parent.widgets[currentIndex] = obj;

            scope.$on('$destroy', function () {
               index--;
            });
...

在视图中:

k-data-source="$parent.widgets[{{index}}].datasource"