AngularJS指令访问相同的作用域对象-避免覆盖

阿塔纳斯·博日科夫(Atanas Bozhkov)

我试图将一个有角度的对象包装到一个模板中,然后我应该可以使用指令对其进行实例化。在这种情况下,每个指令都是一种小部件。

问题出在我编写的指令基于相同的类型这一事实上,因此在实例化指令时,我会在全局范围内跟踪小部件对象。我有以下几方面的东西:

.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在不同阶段将实例分开。

有没有一种方法可以使用全局对象来跟踪指令的基础对象,但仍让它们在运行时传递不同的索引?

延斯·纽鲍尔(Jens Neubauer)

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

.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"

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章