我试图通过将angularJS中的RESTful调用移动到像这样的工厂来改进应用程序中的代码:
在app.js
var myApp = angular.module('myApp', ['ngRoute','ngResource']);
在services.js
中swof.factory('engineerService', function($resource)
{
var data = $resource('/api/engineers/:empid',{empid: "@empid"},
{
'get':
{ method:'GET'},
'save':
{method:'POST'},
'query':
{method:'GET',
transformResponse: function(data)
{
return angular.fromJson(data);
},
isArray:true},
'remove':
{method:'DELETE'},
'delete':
{method:'DELETE'}
});
return data;
});
在controller.js
中engineerService.query().$promise.then(function(data)
{
$scope.engineers = data;
typeof $scope.engineers;
console.log("[in]", $scope.engineers);
$scope.$apply;
});
console.log("[out]", $scope.engineers);
在engineer.html页面中引用了控制器,其想法是显示$ scope.engineer的工程师列表。
Chrome控制台中的输出如下:
由于某些原因,我无法将REST查询返回的数据显示在带有$ promise的控制器部分之外。
有人可以帮帮我吗?
答案 0 :(得分:0)
这是解决方案。首先是服务部分:
swof.factory('engineerService', function($resource)
{
var data = $resource('/api/engineers/:empid',{empid: "@empid"},
{
'get':
{ method:'GET'},
'save':
{method:'POST'},
'query':
{method:'GET',
transformResponse: function(data)
{
return angular.fromJson(data);
},
isArray:true},
'remove':
{method:'DELETE'},
'delete':
{method:'DELETE'}
});
return data;
});
现在为控制器:
swof.controller('engineerController', ['$scope', '$log', '$http', 'engSchedService', 'engineerService', function($scope, $log, $http, engSchedService, engineerService ) {
engineerService.query().$promise.then(function(data)
{
$scope.engineers = data;
});
}]);
使用ngrepeat在html中访问$ scope.engineers中的值,如下所示:
<tbody ng-repeat="engineer in (filtered = (engineers | filter: query | filter: searchKeyword | orderBy: orderByField:reverseSort))">
非常感谢为此提供帮助的所有人。 ģ