通过传递第一个API值在ng-repeat内调用另一个API

时间:2017-06-26 11:37:24

标签: javascript jquery angularjs spring-boot

我有一个角度应用程序,我需要调用Web服务。我必须调用两个不同的URL来获取数据。在我的第一个URL就像  的 ==> abc.com/student/3 这是学生名单。当我在第二个URL中传递学生ID为3时,我需要从第二个URL获取父名,这是另一个URL abc.com/parent/idofStudent3

我能够检索第一个URL数据但是我无法通过在ng-repeat中传递第一个记录数据来检索第二个URL数据。您能帮我解决一下如何在网页中检索父姓名吗?

Html Page

<h1 ng-repeat="x in myWelcome">
{{x.firstname}} || {{x.parentId}} </h1>

这里不是显示parentid,而是通过传递parentId作为参数来调用另一个Web服务来显示父名称。如何在这里打电话给另一个网络服务?

<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
        $http.get("abc.com/student/3")
            .then(function(response) {
                $scope.myWelcome = response.data;
            });
    });
</script>

==&GT;第一个Web服务响应如下:

 {
    "student":[
    {
         "name":"john",
         "parentId": 12,
         "address":"NYC"
    },
    {
         "name":"Rohi",
         "parentId": 14,
         "address":"NJ"
    },
 ]
}

==&GT;当parentId = 12时,第二个webservice响应是这样的:

{
   "firstName": "Sr. John",
}
======> when parentId 14

{
    "firstName": "Sr. Rohi",
}


-------------------------
firstname || parentName
-------------------------
John      ||  Sr. John
Rohi      ||   Sr. Rohi

2 个答案:

答案 0 :(得分:2)

我强烈反对在角ng-repeat内使用控制器功能,因为在摘要周期中会多次调用它。在这种情况下,最好的方法是使用角度指令。您可以将HTML设为

<h1 ng-repeat="x in myWelcome">
{{x.firstname}} || 
 <get-parent-name child='x' parent-name='parentName[$index]'>{{parentName[$index]}}</get-parent-name>
</h1>

在您的控制器中将parentName声明为$scope.parentName = {}

在js文件中添加一个像这样的新指令getParentName

module.directive('getParentName', function ($http) {
    return {
        restrict: 'A',
        scope : {
           child : '=',
           parentName : '='
        },
        link: function (scope, element, attr) {
            var childId = scope.child.id;
            $http.get("abc.com/parent/" + childId)
                .then(function(response) {
                    scope.parentName = response.data.parentName;
                });
        }
    }
});

答案 1 :(得分:0)

您可以尝试进行以下更改。

<h1 ng-repeat="x in myWelcome">
{{x.firstname}} || {{ getparentname(x.parentId) }} </h1>

并在控制器中写入功能。如下所示

 $scope.getparentname = function(data){
    //write you api here
 }