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?
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...
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 idempotentAnother 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.