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>
4

2 回答 2

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>
于 2013-07-20T05:05:10.363 回答
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();
    });
}
于 2013-07-19T08:55:29.067 回答