javascript 带有 Scope 数据数组的 AngularJS 指令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18964570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS Directive with Scope data array
提问by MR.ABC
i've a array. Every item of the array holds data for an directive. The array is created inside a controller.
我有一个数组。数组的每一项都保存指令的数据。该数组是在控制器内部创建的。
The Model
该模型
$scope.myDirectiveData =
[ { title: "First title", content: "First content" },
{ title: "Second title", content: "Second content" } ];
The Directive Template
指令模板
<div class="MyDirective">
<h1>{{myDirectiveData.title}}</h1>
<p>{{myDirectiveData.content}}</p>
</div>
How should i implement the the directive to create a item for any item in the array ? Something like...
我应该如何实现指令来为数组中的任何项目创建一个项目?就像是...
<MyDirective data-ng-repeat="item in myDirectiveData"></MyDirective>
采纳答案by j_walker_dev
Here is an example using a directive. It used ng-repeat to call your directive for each object in the array on your scope. In this fiddle is this what you are looking for.
这是使用指令的示例。它使用 ng-repeat 为作用域上的数组中的每个对象调用指令。在这个小提琴中,这就是你要找的。
angular.module('test', [])
.directive('myDirective', function () {
var template = '<div class="MyDirective">' +
'<h1>{{ data.title }}</h1>' +
'<p>{{ data.content }}</p>' +
'</div>';
return {
template: template,
scope: {
data: '='
},
link: function (scope, element, attrs) {
}
};
})
.controller('TestController', function ($scope) {
$scope.myDirectiveData = [
{ title: "First title", content: "First content" },
{ title: "Second title", content: "Second content" }
];
})
;
Html Edited: the ng-repeat is on the same line as the directive like your question states.
Html 编辑:ng-repeat 与您的问题所述的指令在同一行。
<div ng-app="test" ng-controller="TestController">
<div my-directive data="item" ng-repeat="item in myDirectiveData"></div>
</div>
回答by Mike Driver
<div ng-repeat="item in myDirectiveData">
<h1>{{item.title}}</h1>
<p>{{item.content}}</p>
</div>