我正在使用 AngularJs 1.5 RC 版本。 我有一个 View ,其中我使用 ng-repeat 来迭代集合,如下所示
<tr ng-repeat="user in users">
<td>{{user.JobID}}</td>
<td>{{getManager(user.userID)}}</td>
<td>{{user.StatusDesc}}</td>
<td>{{user.StartedAt}}</td>
</tr>
这里的想法是使用 getManager
函数来获取 users 集合中每个用户的经理名称。
顺便说一句,我必须使用这种方法,因为 API 没有返回所有信息。
这就是 getManager
函数现在的样子。
$scope.getManager = function($id) {
return "John Doe";
}
整个 Controller 如下所示
var app = angular.module('userapp', ['ui.bootstrap']);
app.controller('MainController', ['$scope','$http', function($scope, $http) {
$scope.getUsers = function() {
$http.get("http://localhost/getUsers").
success(function(data, status, headers, config) {
$scope.users = data.resource;
}).
error(function(data, status, headers, config) {
// log error
console.error("An error as encountered. Error follows:");
console.error(data);
});
}
$scope.getManager= function($id) {
return "John Doe";
}
}]);
因此,在我的页面 View 中,我将“John Doe”作为我所有用户的经理。
问题
每当我尝试为用户找到真正的管理员时,问题就开始了。因此,如果我用以下函数替换我的虚拟 getManager
$scope.getManager = function($id) {
$http.get("http://localhost/user/manager/"+$id).
success(function(data, status, headers, config) {
return (data.resource[0].ManagerName);
}).
error(function(data, status, headers, config) {
// log error
console.error("An error as encountered. Error follows:");
console.error(data);
});
}
AngularJs 开始提示并失败,并显示以下内容 https://docs.angularjs.org/error/$rootScope/infdig?p0=10&p1=%5B%5D
您能告诉我这里可能发生什么吗? 请注意,我是一个 Angular 菜鸟,因此非常感谢您的耐心。
谢谢
最佳答案
您应该在 {{}}
插值中以这种方式调用 ajax。它将在每个摘要周期调用并抛出 $rootScope/infdig
错误。
所以我建议您在从服务器检索数据后立即调用 getManager
方法。然后从服务器获取数据后,您需要通过传递 UserId
来调用 getManager
方法(看我更改 getManager
实现以通过返回数据返回 managerName )。获取 managerName 后,您需要将该经理名称绑定(bind)到用户对象并在 HTML 上使用 {{user.ManagerName}}
。
标记
<tr ng-repeat="user in users">
<td>{{user.JobID}}</td>
<td>{{user.managerName}}</td>
<td>{{user.StatusDesc}}</td>
<td>{{user.StartedAt}}</td>
</tr>
代码
$scope.getUsers = function() {
$http.get("http://localhost/getUsers")
.success(function(data, status, headers, config) {
$scope.users = data.resource;
angular.forEach($scope.users, function(user){
(function(u){
$scope.getManager(u.UserID).then(function(name){
u.ManagerName = data;
})
})(user);
})
})
};
$scope.getManager = function($id) {
return $http.get("http://localhost/user/manager/"+$id).
then(function(response) {
var data = response.data;
return (data.resource[0].ManagerName);
},function(error) {
console.error("An error as encountered. Error follows:");
});
};
Side Note
Don't use .success & .error function on $http calls as they are deprecated.
关于javascript - 在 ng-repeat 中调用另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34770884/