隔离范围无法访问范围链中较高的变量

时间:2014-07-11 16:34:40

标签: javascript angularjs angularjs-directive angularjs-scope

在任何人将此标记为重复之前,我在SO上发现了类似的问题:

  1. Isolate scope variable is undefned
  2. unable to access rootscope var in directive scope
  3. 但我的本身特别是一个不同的问题。

    我有一个带有隔离范围的指令。在其后链接功能中,我尝试访问恰好位于根(最顶层)范围内的变量。在我孤立的范围内,我尝试了myVar: '@'myVar: '=',但没有一个工作,myVar在指令范围内是undefined。以下是我的指令的返回声明:

    {
        restrict: 'E',
        replace: true,
        transclude: true,
        template: tmpl,
    
        scope: {
            myVar: '@'
        },
    
        link: {
            post: function ($scope) {
                // $scope.myVar is undefined
                // $scope.$root.myVar is defined
            }
        }
    }
    

    在我的控制台中,我记录了当前的范围对象,我可以跟踪$parent一直到根,并看到var在那里,所以var也可以通过$root访问目前的范围。

    我的问题是,为什么'@''='在这种情况下不起作用?是因为var在除了直接父项之外的链中被定义得更高,或者因为中间的某些父作用域本身就是一个孤立的作用域并且打破了对该var的引用链?

1 个答案:

答案 0 :(得分:2)

如果您有一个孤立的范围,那么无论您希望它用于my-val,您都希望传递给您的指令。举个简单的例子,我们可以在html中说明这一点:

 <my-test my-var='{{test}}'></my-test>

我们的主控制器将有一个名为test的范围变量。

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.test = 'World';
});

因此,如果您注意到该指令正在设置my-var = {{test}}

现在我们指令myVar的范围变量将绑定到该值。

app.directive('myTest', function()  {
  return {
    restrict: 'E',
    replace: true,
    transclude: true,
    template: '<span>{{myVar}}</span>',

    scope: {
        myVar: '@'
    },

    link: {
        post: function (scope) {
            console.log(scope.myVar);
        }
    }
  }
});

这是一个简单的演示:http://plnkr.co/edit/rkbLJ0dJk4OrtyOD3c8w?p=preview