问题
I have this factory in angular:
'use strict';
angular.module('finansiiApp')
.factory('transactions', function ($http) {
var transactions = [];
$http.get("/api/transactions.json")
.success(function(data, status){
transactions = data;
});
// Public API here
return {
getTransactions: function () {
return transactions;
},
addTransaction: function(transaction){
transactions.push(transaction);
}
};
});
This is my controller:
'use strict';
angular.module('finansiiApp')
.controller('MainCtrl', function ($scope, transactions) {
$scope.searchText = "";
$scope.filterPrimanja = $scope.filterTrosoci = true;
console.log(transactions);
$scope.transactions = transactions.getTransactions();
$scope.clicked = function(index){
console.log(index);
}
});
Now as you probably guessed, my data in the controller(where i call the getTransactions method) is not updated on success. How would i go about making this work?
回答1:
There are a few things you could change. (and ways you could change them). 1 being the most suggested/correct.
Use promises and callbacks in your controller so...
// your controller... ($scope.transactions line) transactions.getTransactions().then(function(data){ $scope.transactions = data; } // your service.. angular...factory('transactions',function($http,$q){ var transactions = []; return { getTransactions: function(){ //is a request needed? if(transactions.length > 0){ var deferred = $q.defer(); deferred.resolve(transactions); return deferred.promise; } return $http.get("/api/transactions.json").then(function(result){ //modify collection of transactions... transactions = result.data; return transactions; // this is data ^^ in the controller }); } addTransaction: function(transaction){ //do more http stuff? //wrap function in promise so its consistent and will also run digest. var deferred = $q.defer(); transactions.push(transaction); deferred.resolve(transactions); return deferred.promise; } } });
Modify
var transactions = [];
instead of just wiping it out. eg. iterate over new data and push/pop unshift, concat w/e Objects bound in angular need to be idempotent
Another thing to keep in mind is that services are instantiated just once. While controllers are being created and destroyed all the time.. You might not have to make the request every time so perhaps before returning $http promise in getTransactions
you could check to see if you need to make the request. Then manually use a promise.
来源:https://stackoverflow.com/questions/21127623/angularjs-how-would-i-return-value-from-factory-if-the-data-is-fetched-with-ht