[英]How to call a function to renders items in a `ng-repeat` directive?
I am writing a directive to output a list of items. 我正在写一条指令以输出项目列表。 Those items are meant to be read from a JSON somewhere. 这些项目应从某个地方的JSON读取。
Now, I want to render each item accordingly to a method that would be passed to the directive. 现在,我想将每个项目相应地呈现给将传递给指令的方法。 Then, in my template, I call the method, passing it the item to be rendered. 然后,在模板中,我调用方法,将要渲染的项目传递给该方法。
The method itself is called, but the passed item is undefined
. 该方法本身被调用,但是传递的项目是undefined
。
Where am I wrong, and how to acheive this? 我在哪里错了,如何实现呢?
You can see and play with the code here: https://jsfiddle.net/zpntqayr/ 您可以在此处查看和使用代码: https : //jsfiddle.net/zpntqayr/
Here is the code: 这是代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.1/angular.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<drop-down-list items="data" display-item="itemToString(item)" />
</div>
<script>
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function ($scope, $http) {
$scope.data = [{ "Name": "Value 1", "Value": 1 }, { "Name": "Value 2", "Value": 2 }, { "Name": "Value 3", "Value": 3 }, ] ;
$scope.itemToString = function (item) {
// alert(item);
return item.Name;
};
});
myApp.directive('dropDownList', function () {
return {
restrict: 'E',
replace: true,
scope: {
items: '=',
displayItem: '&'
},
template: '<ul><li ng-repeat="item in items">{{displayItem(item)}}</li></ul>',
};
});
</script>
</body>
</html>
Just replace the code in the directive template as below: 只需替换指令模板中的代码,如下所示:
{{displayItem(item)}}
with 同
{{displayItem({item: item})}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.