[英]How to call a function to renders items in a `ng-repeat` directive?
我正在写一条指令以输出项目列表。 这些项目应从某个地方的JSON读取。
现在,我想将每个项目相应地呈现给将传递给指令的方法。 然后,在模板中,我调用方法,将要渲染的项目传递给该方法。
该方法本身被调用,但是传递的项目是undefined
。
我在哪里错了,如何实现呢?
您可以在此处查看和使用代码: https : //jsfiddle.net/zpntqayr/
这是代码:
<!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>
只需替换指令模板中的代码,如下所示:
{{displayItem(item)}}
同
{{displayItem({item: item})}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.