【问题标题】:Custom directive with templateUrl and ng-repeat带有 templateUrl 和 ng-repeat 的自定义指令
【发布时间】:2013-10-04 09:26:36
【问题描述】:

我已经研究这个问题好几个小时了,终于i reproduced it on plunker

这是我的问题:

当使用外部资源作为模板的自定义指令与 ng-repeat 组合时,模型更改时视图无法正确呈现。

在我的例子中,点击链接将替换模型,但旧数据没有被清理。

如果我使用template: 'stringTemplate' 而不是templateUrl: 'urlToTemplate',它就可以正常工作。 还是不知道是bug还是什么...

部分代码:

angular.module('test', [])
    .run(function($rootScope) {
        $rootScope.topics = [{
            content: 'Click here to change reply',
            replys: [{
                content: 'Reply test...',
            }]
        }];
    })
    .directive('topic', function() {
        return {
            replace: true,
            restrict: 'E',
            templateUrl: 'topic.htm',
            link: function(scope) {
                scope.reply = function(input) {
                    scope.topic.replys = [{ content: '"Reply test..." should be replaced, but it\'s not!' }];
                }
            }
        };
    })
    .directive('reply', function() {
        return {
            replace: true,
            restrict: 'E',
            // template: '<div><div ng-bind="reply.content"></div></div>' //this works fine
            templateUrl: 'reply.htm' // same content
        };
    });

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

    我做了一些研究,看来你并不孤单:

    https://github.com/angular/angular.js/issues/2151

    用户 ishw 提到,作为快速修复:

    “对于那些可能还没有意识到的人:这是因为您的 ng-repeat 位于指令模板中的根元素上。将您的 ng-repeat 包裹在任何元素中都可以。”

    I tried this with your plunkr and it seems to be working:

      <div> 
          <div class="topic" ng-bind="topic.content" ng-click="reply()"></div>
          <div ng-repeat="reply in topic.replys"><reply></reply></div>
      </div>
    

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 2015-03-06
      • 1970-01-01
      • 2013-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 2014-10-26
      相关资源
      最近更新 更多