javascript - AngularJS 指令模板中的 ng-repeat

标签 javascript angularjs

为什么我的外部模板不使用 ng-repeat 渲染项目?

--- AngularJS 1.1.5

我偶然发现 this bug 但我不确定这是否是同一个问题?如果是的话有什么解决方法吗?

这是一个 Plunker 使用静态列表,但解决方案需要支持两种方式绑定(bind),因为数据是动态的。 (无论如何,这就是它应该如何工作的......)

Controller

.controller('main', ['$scope',function($scope) {
  $scope.items = ['a','b','c'];
}])

指令

.directive('items', function() {
    return {
        restrict: 'E',
        replace: true,
        controller: 'main',
        templateUrl: 'items.html',
        link: function(scope, controller) {
        }
    };
})

items.html

<div ng-repeat="item in items">
    {{item}}
</div>

最佳答案

这是因为您的指令使用的模板没有根元素,请尝试:

<div>
  <h1>What?</h1>
  <div ng-repeat="item in items">
    {{item}}
  </div>
</div>

用于模板。

编辑:为了理解这一点,我们可以看看 Angular 本身的来源。负责此的编译方法可以查看 here 。罪魁祸首是 mergeTemplateAttributes,当查看此处的意图时,对一个根的需求就变得显而易见:当替换 DOM 节点时,Angular 需要传递属性。当获取的模板中有多个节点时,它将抛出一个错误,因为它无法决定将原始属性应用到哪个节点(有关抛出的错误,请参阅 here)。

开发者的引言:

When the element is replaced with HTML template then the new on the template need to be merged with the existing attributes in the DOM. The desired effect is to have both of the attributes present.

关于javascript - AngularJS 指令模板中的 ng-repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18020181/

相关文章:

javascript - AngularJS Ui-grid DataTables,如何避免多次重复

javascript - 使用 karma-browserify 对 AngularJS 应用程序进行单元测试

javascript - 映射后从js中删除属性名称

javascript - 使用 jQuery 调整与父 div 相关的 div 大小

javascript - 如何永久存储我的链接点击次数?

AngularJS 等待范围变量从自定义指令评估

angularjs - 渲染在我的自定义指令中的 setViewValue 之后吃掉空格

javascript - AngularJS:向 ng-repeat 内的图像添加切换功能

javascript - 选择后隐藏文件输入

javascript - Vuetify 底部导航切割内容