2013-07-19 36 views
0

我试图在指令中输出子元素ID,但它保持打印非插值的值。我不知道如何实现....请帮助。指令:链接功能的孩子不插值

我努力学习的角度...

////////////////////// 
//Directive example 
app.directive('simpleNumber', ['$http', '$compile', function($http, $compile) { 

return { 
    restrict: 'A',  /*Example: <span simple-number></span>*/ 
    terminal: true, 
    transclude: true, 
    replace: true,  /*Replace <simple-number-ctrl> tag with below template*/ 
    template: "<div><div id=\"{{$id}}\"></div></div> ", 

    scope: { /*data-binding to parent scope*/ 
     ctrlWidth: "@",  /*one way binding*/ 
     strNumber: "=",  /*two way binding*/ 
     onWidthChanged: "&"  /*Event function fired*/ 
    }, 

    link: function($scope, elm, attrs) { 
     console.log(elm.children()[0].id);     //This is printing {{$id}} !!! I AM CONFUSED 
    } 
}; 

}]); 


<span simple-number ctrl-width="100px" str-number="numberText" on-width-changed="onWidthChanged(width);"><font color=green>Transcluded text</font></span> 

回答

0

当结合函数被调用时,{{ }}绑定尚未评估,所以你仍然有它们作为原始文本。 $ digest循环完成后,您将获得正确的值。 如果您想更好地理解正在发生的事情,请在链接功能中使用此功能。

link: function($scope, elm, attrs) { 
    console.log("bindings not evaluated yet:",element.html()); 
    var unwatch = scope.$watch(function(){ 
     console.log("after $digest, bindings are evaluated",element.html()); 
     unwatch(); 
    }); 
} 
+0

以下是控制台输出 **之前绑定进行评估** 绑定还未评估:

摘要叫** **后(按照您的例子) $消化后,绑定被评估

+0

奇怪,我记得在发送解决方案之前测试它。你可以尝试没有unwatch()调用吗? – Yann

0

我已经使用$ timeout解决了这个问题(见下面的代码)。我不知道它为什么这样工作。有人可以提供解释吗?

////////////////////// 
//Directive example 
app.directive('simpleNumber', ['$http', '$compile', function($http, $compile) { 

return { 
    restrict: 'A',  /*Example: <span simple-number></span>*/ 
    transclude: true, 
    replace: true,  /*Replace <simple-number-ctrl> tag with below template*/ 
    template: "<div><div id=\"{{$id}}\"></div></div> ", 

    link: function($scope, elm, attrs) { 
     //Print children ID's 
     var __debugOutputChildrenInfo = function(children) 
     { 
      for(var i = 0; i < children.length; i++) 
       console.log(children[i].id); 
     } 

     var children = elm.children(); 
     __debugOutputChildrenInfo(children); //Prints {{$id}} [Shouldn't binding have been resolved by now?] 

     //Don't understand why this is working...need explanation? 
     $timeout(function() { 
      __debugOutputChildrenInfo(children); //Prints 002 [THIS IS WHAT I WANTED..NEED EXPLANATION] 
     }); 
    } 
}; 

}]); 


<span simple-number ctrl-width="100px" str-number="numberText" on-width-changed="onWidthChanged(width);"><font color=green>Transcluded text</font></span> 
相关问题