Creating a basic control panel using AngularJS + Rest API.
Developing a factory to handle API requests (GET, POST) and pass back necessary data to a success callback. The processed data must update the $scope
, taking into account potential server-side form field errors returned by the API.
The challenge lies in manipulating the $scope
without directly altering it within the factory itself, as factories should not have access to scopes. It is also undesirable to repetitively process data in the success callback for each API request.
What is the most effective "Angular way" to tackle this issue?
A potential solution involves defining a function external to the Angular application and passing it the $scope along with the required data.
This workaround may seem less than ideal (as shown 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....
}
}