Building a simple control panel in AngularJS + Rest API.
Built a simple factory that makes the API request (GET, POST)
and returns necessary data to a success callback. The return data needs to be processed and alter the $scope
since the API can return server-side form field errors.
I cannot build the processing/altering $scope
within the factory since the factory doesn't (and shouldn't) have access to the scope. I would prefer not to processing/applying in the success callback since it would be repetitive (once per API request).
What is the best "Angular way" to solve this problem?
One possible solution is to have a function exist outside of the Angular application and then just pass it the $scope and necessary data.
This feel like a poor work around (see below).
myApp.controller("saveForm", ["$scope", "api", function($scope, api), function() {
...
$scope.submit = function() {
api("POST", url, $scope.data, function(data) {
//onSuccess
processData($scope, data);
});
}
...
}]);
myApp.factory('api', ['$http', function($http) {
return function(method, url, input, success, error) {
//Retrieve data from API. Note that factory DOES NOT have access to $scope.
$http(...
}
}]);
var processData = function(scope, data) {
angular.forEach(data, function(value, key)) {
scope....
}
}