[英]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.