如何调用函数以在“ng-repeat”指令中呈现项目

How to call a function to renders items in a `ng-repeat` directive?

本文关键字:指令 ng-repeat 项目 何调用 调用 函数      更新时间:2023-09-26

我正在编写一个指令来输出项目列表。这些项目旨在从某处的 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})}}