【问题标题】:AngularJS directives accessing the same scope object - avoid overwriteAngularJS 指令访问同一个作用域对象——避免覆盖
【发布时间】:2014-08-18 20:52:04
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案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"
    

    【讨论】:

    • 使用 widgets[{{$$index}}].datasource 会产生 $parse 错误。 link 为什么是双 $ 符号?
    • 它会产生一个解析错误,因为` $$index ` 不能解析任何东西。我已经双重检查了我的代码。应该是正确的。有什么想法吗?
    • 对不起,我错了,应该只有$index。我在想$$hashkey
    • 我也试过了,但也没有用。我将能够在星期一再次测试。有什么想法吗?
    • 等等,你想访问指令初始化的索引吗?那是行不通的。如果在父作用域中设置索引(通过设置scope: false 来实现),指令的每个后续实例化都会覆盖它。我将编辑我的答案。
    猜你喜欢
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多