如何调用一个函数来呈现 `ng-repeat` 指令中的项目?
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})}}
我正在编写一个输出项目列表的指令。这些项目应该从某个地方的 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})}}