I'm currently trying to build my first angular app, and I could need a little help.
I'm accessing a REST service with the standard $resource actions:
angular.module('wtrack', ['ngResource']).
factory('WtrackAPI', function($resource) {
var WtrackAPI = $resource('http://hostname/wtrack/api/w/:id');
return WtrackAPI;
});
And this is my controller:
function ListCtrl($scope, $timeout, WtrackAPI){
$scope.wdata = WtrackAPI.query(); // a list of objects displayed in my view
$scope.addEntry = function() { // adding an object to the list
console.log("Adding Entry");
var entry = {day: $scope.wdata.day, value: $scope.wdata.value};
WtrackAPI.save(entry,
function(){console.log("WTF do I need to do here to rerun WtrackAPI.query()");});
};
}
What I'd want to do is basically update my model by executing $scope.wdata = WtrackAPI.query();
again once the save() is done. I suspect the angular way would be to just $scope.wdata.push(entry)
, but in this case the database adds some data to the entry with triggers and does some complex sorting, so I really want to roundtrip and reload the whole list using query. How can I make this happen? Just calling $scope.wdata = WtrackAPI.query();
in the save callback doesn't work as $scope apparently doesn't exist in there. I tried a few other things with $emit and $rootScope etc, but all that did was making me really confused. So please, can anybody give me a hint on what's the proper way to do that?
The $scope
object should be accessible in the closure scope so you should be able to write:
function ListCtrl($scope, $timeout, WtrackAPI){
$scope.wdata = WtrackAPI.query(); // a list of objects displayed in my view
$scope.addEntry = function() { // adding an object to the list
var entry = {day: $scope.wdata.day, value: $scope.wdata.value};
WtrackAPI.save(entry, function() {
//$scope should be accessible here
$scope.wdata = WtrackAPI.query();
});
};
}