I've been learning angular a bit here and there, but I don't quite get what the angular way of handling success/error responses from the server would be. The typical jQuery way to do it would be:
- Serialize data from form
- $.post the data to server
- server validates data, responds with success or error data
- use jQuery to maniuplate DOM to display success/error data from server.
In angular, we have directives that manipulate the DOM and we have controllers that deal with the models. Say we have the following:
form.html
<div ng-controller="myController">
<span class="hidden success-message"></span>
<form>
<label> Name </label>
<input type="text" name="name" ng-model="name">
<span class="name-error hidden"></span>
<label> Occupation </label>
<input type="text" name="occupation" ng-model="occupation">
<span class="occupation-error hidden"></span>
<input submit-directive type="submit" id="submit" value="Submit">
</form>
</div>
app.js
angular.module('app', []).controller('myController', [$scope, $http, function($scope, $http) {
$scope.name = "";
$scope.occupation = "";
$scope.doSubmit: function(formData) {
$http.post("/save", formData)
.success(function(response) {
$scope.name = response['name']
$scope.occupation = response['occupation']
// How to pass success messages back to directive?
}.fail(function(err) {
// How to pass error messages back to directive?
}
}
});
angular.module('app', []).directive('submit-directive', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.click(function() {
// Pass form data back to controller
scope.$apply('doSubmit(\"' + $("form").serialize() +'\")');
});
// How do I get the success/fail results from the Controller so that I can manipulate the DOM?
}
};
});
Here, a user enters their name
and occupation
. Upon submitting, the directive grabs the form data and presents it to the controller for a POST request. When the response is returned, the directive should either display a success message or display the error messages.
It's not clear how I would pass the response from the controller to the directive for DOM manipulation.
The only way I've thought of is to create a $watch
:
// in controller
$scope.isFormPostSuccess = false;
$scope.formResponse = null;
// ....
.success(function(response) {
$scope.isFormPostSuccess = true;
$scope.formResponse = response;
}.fail(function(err) {
$scope.isFormPostSuccess = false;
$scope.formResponse = err;
}
Then in the directive, I would watch those variables for changes and act accordingly. However, this way of doing it feels very messy and doesn't seem to scale well for larger applications or when having many independent forms. I could also move all the DOM manipulation into the controller, but that's just bad design.
What is the proper angular way?