我有一个函数通过$http.Get
方法从服务器获取数据。收到数据后我需要在另一个函数上使用它。任何人都可以帮助我如何使用数据。
var app = angular.module("app", []);
app.factory('itemsFactory', function ($http) {
var factory = {};
factory.getItems = function () {
return $http.get('.//davidstrans.json')
};
return factory;
});
app.controller('UsersTransController', function ($scope, itemsFactory) {
itemsFactory.getItems().success(function (data) {
$scope.users = data;
});});
之后我有一个动态获取类型的函数:
function groupBy(arr, key) {
var newArr = []
, types = {}
, newItem, i, j, cur;
for (i = 0, j = arr.length; i < j; i++) {
cur = arr[i];
if (!(cur[key] in types)) {
types[cur[key]] = {
type: cur[key]
, data: []
};
newArr.push(types[cur[key]]);
}
types[cur[key]].data.push(cur);
}
return newArr;
};
对于这个函数,我必须使用$scope.users=data;
值。
谁能帮我?提前谢谢。
答案 0 :(得分:-1)
请在代码中进行相应更改:
var app = angular.module("app", []);
app.factory('itemsFactory', function ($http) {
var factory = {};
factory.getItems = function (successCallBack,errorCallBack) {
$http({
method: 'GET',
url: './/davidstrans.json'
}).then(function(response) {
// this callback will be called asynchronously
// when the response is available
successCallBack(response);
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
errorCallBack(response);
});
};
return factory;
});
并在app.controller中:
app.controller('UsersTransController', function ($scope, itemsFactory) {
var successCallBack = function(data){
$scope.users = data;
}
var errorCallBack = function (data){
//if you want to show any error
}
itemsFactory.getItems(successCallBack, errorCallBack);
});