AngularJS范围值在链接中未定义

时间:2015-06-18 22:01:38

标签: angularjs angularjs-directive angularjs-scope

我正在尝试在初始化指令时找出具有范围和链接的内容。我在树控制器中有一个指令,用于在分支点显示详细信息:

<typelists sub="branch.subBranches[0]"></typelists>

处理该分支信息的(相关部分)指令如下:

listsApp.directive(
    'typelists',
    function($rootScope) {
        return {
            restrict: 'EA',
            replace: true,
            scope: {
                branch : '=sub'
            },
            templateUrl: templateDir + '/typelists.html',
            link: function (scope, element, attrs) {
                console.log(scope,scope.branch); // DEBUG

                // other stuff
                //  (including a working reload() and refresh() methods)

                scope.subject = 'Type' + scope.branch.model.getFilter() + 'Lists';

                // catch $rootScope.$broadcasts for this branch
                $rootScope.$on( scope.subject+'Refresh', function() { scope.refresh(); ) } );
                $rootScope.$on( scope.subject+'Reload', function() { scope.reload(); } );
            }
        };

现在,让我感到困惑的是,在// DEBUG行中,我可以看到.branch仅在范围的输出中按预期填充,但scope.branch显示为未定义。 这意味着当我尝试在下面设置scope.subject时,而不是从父类型返回一个typeId,我得到'未定义',所以而不是获得一个独特的分支标记,如'Type1Lists'我得到' TypeundefinedLists',因此我的$ watch表功能无法正常触发。

为什么我无法访问scope.branch或为什么在我尝试时显示为未定义? (特别是当我可以在同一个console.log输出中看到它作为范围的一部分时?)

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

newbody = ntob('').join(map(str, newbody)) 如何填充?我敢打赌,这个值是在指令的branch.subBranches[0]函数运行之后设置的。

您可以使指令适应这些更改,如下所示:

link

或者,只在数据准备就绪时实例化指令:

var unwatch = scope.$watch("scope.branch", function(v){
  if (v) {
    unwatch(); // removes the watch when value is not undefined
    init(); // run your init code
  }
});

<强> P.S。

<typelists ng-if="branch.subBranches[0] !== undefined" sub="branch.subBranches[0]"></typelists> 显示数据的原因是(至少在Chrome中)控制台&#34;渲染&#34;在记录时不会发生 - 换句话说,当你调用console.log时,数据仍然不存在,但它会在控制台读取数据之前到达那里以进行渲染。

答案 1 :(得分:0)

我敢打赌这种情况正在发生,因为你在父指令链接函数中设置了branch.subBranches[0]

然而,Angular以自下而上的方式链接指令。即父项之前,将调用子指令链接功能。因此,如果您在父指令链接函数中设置'branch.subBranches [0]',那么当运行子指令链接函数(先运行)时,它仍然是未定义的。

Angular指令DOM编译的时间是这样的,控制器首先从上到下(父对象)运行,然后链接回到底部(父对象)。

因此,要解决问题,最简单的方法是在父控制器函数中定义/设置branch.subBranches[0](与链接相对)。

修改

以下是我怀疑在你的情况下发生的事情(在跑步时打开控制台):

http://plnkr.co/edit/YMLAtGc38oc3vVqebH3Z?p=preview

以下是建议修补程序的附件:

http://plnkr.co/edit/EjrSorCvFLcDkODe2Anm?p=preview