I am very new to angular and javascript in general and familiar enough with php and laravel that today I started a little learner app that join the two. I have angular displaying a list of resources returned to it from laravel. I have a text field that can be submitted to laravel which validates the input and stores it in the db and angular pushes the input field to the list. This works fine. however when the validation fails the input is still pushed to the list in the dom. What I want to do is inspect the response from the server for errors (returned as json) and only if there are none update the dom with the text field.
html
<!doctype html>
<html lang="en" ng-app>
<head>
<meta charset="UTF-8">
<title>Loadmaster</title>
</head>
<body ng-controller="DzsController">
<h1>Dropzones</br>
<small ng-if="open()">{{ open() }} Open</small></br>
<small ng-if="jumping()">{{ jumping() }} Jumping Right Now!</small>
</h1>
<input type="text" placeholder="Filter dzs" ng-model="search">
<ul>
<li ng-repeat="dz in dzs | filter:search">
{{ dz.name }}
<input type="checkbox" ng-model="dz.open">
<input type="checkbox" ng-model="dz.jumping">
</li>
</ul>
<form ng-submit="addDz()">
<input type="text" placeholder="Add a new dz" ng-model="newDzText" required>
<button type="submit">Add Task</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script src="/js/main.js"></script>
main.js
function DzsController($scope, $http) {
/*$scope.dzs = [
{ name: 'Perris', open: true, jumping: true },
{ name: 'Elsinore', open: false, jumping: false }
];*/
$http.get('/dzs').success(function(dzs) {
$scope.dzs = dzs;
});
$scope.open = function() {
var count = 0;
angular.forEach($scope.dzs, function(dz) {
count += dz.open ? 1 : 0;
});
return count;
};
$scope.jumping = function() {
var count = 0;
angular.forEach($scope.dzs, function(dz) {
count += dz.jumping ? 1 : 0;
});
return count;
};
$scope.addDz = function() {
var dz = {
name: $scope.newDzText,
open: false,
jumping:false
};
//$scope.dzs.push(dz);
$http.post('dzs', dz);
};
}
validation errors json
{"name":["The name field is required."]}
solution
$scope.addDz = function() {
var dz = {
name: $scope.newDzText,
open: false,
jumping:false
};
$http.post('dzs', dz).success(function(data, status) {
if(isDefined(data.errors)) {
console.log(data.errors);
} else {
console.log('no validation errors');
}
});
};