[英]How to pass a collection to a directive in angular.js?
Please forgive my lack of understanding. 请原谅我缺乏理解。
I pass the name of a collection to my directive: 我将集合的名称传递给我的指令:
<ul tag-it tag-src="preview_data.preview.extract.keywords"><li>Tag 1</li><li>Tag 2</li></ul>
The directive is defined: 指令定义如下:
app.directive('tagIt', function (){
return {
restrict: 'A',
link: function(scope,elem, attr) {
elem.tagit();
console.log(attr.tagSrc); //the name of my collection, but how do I access it?
}
}
});
How do I access my collection from the directive and make sure my directive is called when the collection is populated? 如何从指令访问我的集合并确保在填充集合时调用我的指令? Here is how preview_data.preview.extract.keyword
s gets populated. 以下是how preview_data.preview.extract.keyword
填充how preview_data.preview.extract.keyword
。
app.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
console.log('config');
$routeProvider.when("/", {
templateUrl: "/templates/addItem.html",
controller: "AddItemController",
resolve: {
loadData: addItemCtrl.loadData
}
});
});
var addItemCtrl=app.controller("AddItemController", function ($scope, $route, $sce, Preview) {
var title = decodeURIComponent($route.current.params.title);
var ua = decodeURIComponent($route.current.params.ua);
var uri = decodeURIComponent($route.current.params.uri);
$scope.preview_data = {
uri: uri,
title: title,
ua: ua
}
//pass parameters to web preview API
Preview.get(uri, ua, title).then(function (data) {
$scope.preview_data.preview = data;
if (data.embed.html) {
$scope.preview_data.preview.embed.html = $sce.trustAsHtml(data.embed.html);
}
}, function (data) {
alert('Error: no data returned')
});
});
You need to set the variable in the directive scope and set the template to iterate between the tags: 您需要在指令范围中设置变量并将模板设置为在标记之间迭代:
template : '<li data-ng-repeat="tag in tagSrc">{{tag.name}}</li>',
scope : {
tagSrc : '='
},
And will became this: 并将成为这个:
app.directive('tagIt', function (){
return {
restrict: 'A',
template : '<li data-ng-repeat="tag in tagSrc">{{tag.name}}</li>',
scope : {
tagSrc : '='
},
link: function(scope,elem, attr) {
console.log(attr.tagSrc);
}
}
});
the '='
attribute will tells to angular to use a tw way binding with the array passed in the directive declaration in the HTML. '='
属性将告诉angular使用与HTML中的指令声明中传递的数组的tw方式绑定。
Here is a plunker with a working example. 这是一个带有工作示例的plunker。
And here is a good arcticle explaning the directive's attributes and life cycle. 这是一个很好的arcticle解释指令的属性和生命周期。
I hope it helps. 我希望它有所帮助。
[EDIT] [编辑]
If you want just iterate the array, without creating some different behavior in the list items, you can just simply use the ng-repeat directive: 如果您只想迭代数组,而不在列表项中创建一些不同的行为,您只需使用ng-repeat指令:
<ul>
<li data-ng-repeat="tag in tags">{{tag.name}}</li>
<ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.