指令:链接函数子元素不插值

时间:2013-07-19 06:41:03

标签: angularjs-directive

我试图在指令中输出子元素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>

2 个答案:

答案 0 :(得分: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();
    });
}

答案 1 :(得分: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>