我有一个 Angular 应用程序,我需要调用网络服务。我必须调用两个不同的 URL 来获取数据。在我的第一个网址中就像 ==> abc.com/student/3 这是学生列表。另一个 URL 是 abc.com/parent/idofStudent3 当我在第二个 URL 中传递学生 ID 3 时,我需要从第二个 URL 获取家长的名字。
我能够检索第一个 URL 数据,但无法通过在 ng-repeat 中传递第一个记录数据来检索第二个 URL 数据。您能帮我如何在网页中检索家长姓名吗?
HTML 页面
<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>
==> 第一个网络服务响应如下:
{
"student":[
{
"name":"john",
"parentId": 12,
"address":"NYC"
},
{
"name":"Rohi",
"parentId": 14,
"address":"NJ"
},
]
}
==>当parentId=12时,第二个Web服务响应如下:
{
"firstName": "Sr. John",
}
======> when parentId 14
{
"firstName": "Sr. Rohi",
}
-------------------------
firstname || parentName
-------------------------
John || Sr. John
Rohi || Sr. Rohi
最佳答案
我强烈反对在 Angular ng-repeat
中使用 Controller 函数,因为它在摘要周期中被调用多次。在这种情况下,最好的方法是使用 Angular Directive(指令)。您可以将 HTML 设为
<h1 ng-repeat="x in myWelcome">
{{x.firstname}} ||
<get-parent-name child='x' parent-name='parentName[$index]'>{{parentName[$index]}}</get-parent-name>
</h1>
在您的 Controller 中将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;
});
}
}
});
关于javascript - 通过传递第一个 API 值在 ng-repeat 内进行另一个 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44758853/