我有重复的员工。返回的结果字段之一是员工编号,例如“12345”。
如何执行ajax查找并使用相应的名称替换员工编号?
示例: / _ api / web / lists / getByTitle('allStaff')/ items?$ select = fullName& $ filter = userid eq'12345'
将返回:“Doe,John”。
我尝试使用过滤器,但即使我可以看到返回结果,也没有显示任何内容。
<div ng-repeat="emp in employees"">
<i class="fa fa-user"></i> {{emp.id}}
</div>
app.filter('getName', function($http) {
return function(id){
if (id) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('allStaff')/items?$select=fullName&$filter=userid eq '"+id+"'";
$http({
method: 'GET',
url: url,
cache: true,
headers: { "Accept": "application/json;odata=verbose" }
}).success(function (data, status, headers, config) {
userInfo = data.d.results[0].pn;
console.log(userInfo);
}).error(function (data, status, headers, config) {
userInfo = "0";
});
return userInfo;
}
};
});
答案 0 :(得分:2)
过滤功能是同步的,而$http
调用是异步的。 success
回调甚至在过滤函数返回之后才会执行,因此看起来返回值为undefined
。
角度过滤器不适合从API加载数据,并且有一种更简单的方法。将userInfo
添加到相应服务/工厂/控制器中的employees
阵列(这取决于您如何组织代码,但设置$scope.employees
的控制器快速而脏选项)。类似于forEach
通过数组为每个进行API调用并在成功回调中设置employee.userInfo
:
app.controller('EmployeeController', function($scope, $http) {
// $scope.employees is initialized somehow
$scope.employees.forEach(function (employee) {
if (employee.id) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('allStaff')/items?$select=fullName&$filter=userid eq '"+employee.id+"'";
$http({
method: 'GET',
url: url,
cache: true,
headers: { "Accept": "application/json;odata=verbose" }
}).success(function (data) {
employee.userInfo = data.d.results[0].pn;
}).error(function () {
employee.userInfo = "0";
});
}
});
});
在你的模板中:
<div ng-repeat="emp in employees">
<i class="fa fa-user"></i> {{emp.userInfo}}
</div>
由你决定在ajax请求完成之前要做什么,而emp.userInfo
未定义 - 隐藏元素,显示占位符等等。