【问题标题】:Angular: linking transcluded templatesAngular:链接嵌入的模板
【发布时间】:2013-08-26 04:22:14
【问题描述】:

我有一个指令,该指令部分由父作用域中的 ng-repeat 填充,然后侦听器附加在 postLink 中。但是,由于内容是嵌入的,因此无法通过链接时间获得/插值。

我整理了一个JSFiddle example 来演示:

模板:

<script type="text/ng-template" id="directive.html">
        <div>list item count: {{ count }} (should be {{2 + items.length }})</div>
        <div>Transcluded content: <span ng-transclude></span></div>
</script>

<div ng-controller="Ctrl">
    <ul frag>
        <li ng-repeat="item in items">{{ item }}</li>
        <li>4</li>
        <li>5</li>
    </ul>
</div>

代码:

app.directive("frag", function ($http) {
    return {
        restrict: 'A',
        transclude: true,
        templateUrl: 'directive.html',
        link: function (scope, element, attrs) {
            scope.count = element.find("li").length;
            console.log(element);
        },
        controller: function ($scope) {
            $scope.foundB = false;
        }
    };
});

在这种情况下,列表项计数最终为 2,而不是在嵌入后预期的 5。

任何人有任何想法我可以如何使这项工作?期待找到某种我可以观察到的嵌入后事件,然后才进行链接,但找不到。

【问题讨论】:

    标签: angularjs angularjs-directive transclusion


    【解决方案1】:

    您可以使用$timeout 将代码移动到执行队列的末尾,在摘要循环之后:

    app.directive("frag", function ($http, $timeout) {
        return {
            restrict: 'A',
            transclude: true,
            templateUrl: 'directive.html',
            link: function (scope, element, attrs) {
                $timeout(function() {
                    scope.count = element.find("li").length;
                });
            },
            controller: function ($scope, $element) {
                $scope.foundB = false;
            }
        };
    });
    

    http://jsfiddle.net/pnQyA/8/

    【讨论】:

    • Ta - 我一直在使用$timeout 作为最后的手段来保存!希望(a)我错过了一些明显的东西,或者(b)有一些更整洁的东西。
    猜你喜欢
    • 2013-05-26
    • 2022-01-15
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多