Angular 1.5 - Clear form after submit - angularjs

I have read through all of the suggested postings on this, but I can't seem to clear the form fields after I submit.
I am using controller as syntax, but even if I try to use $scope with $setPristine, I still can't make it work.
This SO answer is what I am following:
https://stackoverflow.com/a/37234363/2062075
When I try to copy this code, nothing happens. No errors, nothing is cleared.
Here is my code:
app.controller('HiringRequestCtrl', function ($http) {
var vm = this; //empty object
vm.ctrl = {};
vm.saveChanges = function() {
//console.log(vm);
$http({
method: 'POST',
url: '/hiringrequest/createPost',
data: angular.toJson(vm)
})
.success(function (response) {
//great, now reset the form
vm.ctrl = {};
})
.error(function (errorResponse) {
});
}
});
and my form looks like this:
<div ng-controller="HiringRequestCtrl as ctrl">
<form id="form" name="ctrl.myForm">
...
<input type="text" name="proposalName" ng-model="ctrl.proposalName"/>
<input type="submit" id="saveButton" value="Submit" class="button" ng-click="ctrl.saveChanges()" />
...
</form>
</div>
I would really prefer not to use $scope.

There's some fundamental issues with the way you've structured this. I think your use of vm.ctrl and then also ng-controller="HiringRequestCtrl as ctrl" is confusing you. Below are my recommended [untested] changes. (I would also suggest moving the $http stuff into a service and using .then() and .catch() because .success() and .error() are deprecated).
Controller
.controller('HiringRequestCtrl', function($http) {
var vm = this; // self-referencing local variable required for when promise resolves
vm.model = {};
vm.saveChanges = function() {
$http({
method: 'POST',
url: '/hiringrequest/createPost',
data: angular.toJson(vm.model)
})
.success(function(response) {
//great, now reset the form
vm.model = {}; // this resets the model
vm.myForm.$setPristine(); // this resets the form itself
})
.error(function(errorResponse) {});
}
});
HTML
<div ng-controller="HiringRequestCtrl as ctrl">
<form id="form" name="ctrl.myForm" ng-submit="ctrl.saveChanges()" novalidate>
<input type="text" name="proposalName" ng-model="ctrl.model.proposalName" />
<input type="submit" id="saveButton" value="Submit" class="button" />
</form>
</div>
Update
Service
.service('hiringService', function($http) {
var service = {};
service.createPost = function(model) {
return $http({
method: 'POST',
url: '/hiringrequest/createPost',
data: angular.toJson(model)
});
}
return service;
}
Controller
.controller('HiringRequestCtrl', function(hiringService) {
vm.saveChanges = function() {
hiringService.createPost(model)
.then(function(response) {
// if you need to work with the returned data access using response.data
vm.model = {}; // this resets the model
vm.myForm.$setPristine(); // this resets the form itself
})
.catch(function(error) {
// handle errors
});
}

Related

$scope variable not reloaded

In the controller I have the code below :
//View
<input type="text" value="{{customer.lastName}}" />
//Controller
$scope.getbycode = function (customerCode) {
var deferred = $q.defer(),
getCustomerRequest = {
code: customerCode
};
$http({ method: 'POST', url: 'api/customer/getbycode', data: getCustomerRequest })
.success(function (data) {
deferred.resolve(data);
}).error(function () {
deferred.reject();
});
return deferred.promise;
};
$scope.getbycode($routeParams.customerCode).then(function (data) {
$scope.customer = data.customer;
});
That's work, I see the lastname of Customer.
In the controller I have this code too. This function is called when I ckick on an hyperlink
$scope.reload = function (customerCode) {
$scope.getbycode(customerCode).then(function (data) {
$scope.customer = data.customer;
alert($scope.customer.lastName);
});
};
I change the text in the input and I click on the hyperlink.
The WEBAPI is called, the data returned in the reload function is correct but the view is not updated.
I missed something ?
value="{{customer.lastName}}" will only evaluate expression first time & then it replaces with customer.lastName value which is 1, DOM will look like below
<input type="text" value="1" />
Which had got rid off {{customer.lastName}} value, the changes in scope variable will never happen to that input field.
You should use ng-model there to have two way binding, that will update input & scope value once you update scope value.
<input type="text" ng-model="customer.lastName" />
Demo Plunkr

How to save data values from form in angularjs using fat free framework

I am trying to save data in sql using fat free framework. i used front end in angularjs. i send data using angular ng-submit button. ajax Post data but not get in fat free please solve this problem. i am new in fat free.
here is my html code:
<form id="userRegister" name="registration" ng-submit="register1(formData)" ng-controller="Ctrl1">
<div class="sf-steps-form sf-radius">
<div class="sf_columns column_3">
<input ng-model="formData.email" id="email" type="email" name="email" placeholder="Email*" data-required="true" >
</div>
<div class="sf_columns column_3">
<input ng-model="formData.password" id="password" type="password" name="password" placeholder="Secret Word*" data-required="true" >
</div>
</div>
<button type="submit" id="sf-next" class="sf-button">Save</button>
</form>
here is my app.js code:
sampleApp.controller("Ctrl1", function($scope, $http) {
$scope.formData = {};
$scope.register1 = function() {
console.log($scope.formData);
$http({
method : 'POST',
url : 'addstep',
data : $scope.formData,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
$scope.errorEmail = data.errors.email;
$scope.errorPassword = data.errors.password;
} else {
$scope.message = data.message;
}
});
};
});
here is my idex.php fat free framework code:
$f3->route('GET|POST /addstep',
function($f3) {
//print_r($f3);
$users = new DB\SQL\Mapper($f3->get('DB'),'user');
$users->copyFrom('POST');
$users->save();
$f3->set('content','step1.htm');
echo View::instance()->render('layout.htm');
}
);
The ajax post data properly but not save in db please help.
Check $f3->get('BODY');
You might need to json_decode;
Most likely the data is sent via PUT
I actually just dealt with this on an application using f3 and angular. If you haven't figured it out I have been pretty successful with this:
I have an angular $http service:
angular.module('myApp')
.service('apiConnector', function apiConnector($http) {
var apiBase = '';
var obj = {};
obj.get = function(q) {
return $http.get(apiBase + q).then(function(results) {
return results.data;
});
};
obj.post = function(q, object) {
return $http.post(apiBase + q, object).then(function(results) {
return results.data;
});
};
obj.put = function(q, object) {
return $http.put(apiBase + q, object).then(function(results) {
return results.data;
});
};
obj.delete = function(q) {
return $http.delete(apiBase + q).then(function(results) {
return results.data;
});
};
return obj;
});
Then I use this service in my angular controllers like so:
angular.module('myApp')
.controller('homeController',function($scope, $state, $stateParams, $timeout, apiConnector){
$scope.user = {};
apiConnector.get('/api/users/'+$stateParams.id)
.then(function(res){
if (res.success) {
$scope.user = res.data;
}
},function(err){
console.log(err);
});
$scope.updateUser = function(user) {
apiConnector.post('/api/users/'+$stateParams.id,user)
.then(function(res){
if (res.success) {
alert('updated');
}
}, function(err){
console.log(err);
});
};
});
Lastly the f3 controller. I am using [maps] for my routes to get a truly restful interface, and my routes use an #id param. I collect data like so:
class Item {
function get($app,$params) {
$id = $params['id'];
$user = new \Models\User();
$user->load(array('id = ?',$id));
echo json_encode($user->cast());
}
function post($app,$params) {
$POST = json_decode(file_get_contents('php://input'));
$id = $params['id'];
$user = new \Models\User();
$user->load(array('id = ?',$id));
$user->copyfrom($POST);
$user->touch('created');
$user->save();
echo json_encode(array('message' => 'Successfully updated user!'));
}
function put() {}
function delete() {}
}
Hope that helps!

Login in angularjs

I have an idea of how to use post method for login, however, our new requirement is my API team has provided get method. How is this used in angular? Please help me. I am stuck on this problem as I am new to angular. Below is the API for get method:
http://183.82.48/HospitalManagementSystem/Service1.svc/LoginVerification/{EMAILID}/{PASSWORD}
You can try to construct the URI yourself.
<form ng-app="login" ng-controller="loginCtrl">
<span>Email</span><input ng-model="emailId" type="text" required><br>
<span>Password</span><input ng-model="password" type="password" required><br>
<button ng-click="login()">Login</button>
</form>
<script>
var app = angular.module('login', []);
app.controller('loginCtrl', function($scope, $http) {
$scope.login = function() {
$http.get('http://183.82.0.48/HospitalManagementSystem/Service1.svc/LoginVerification/' + $scope.emailId + '/' + $scope.password).then(
function (response) {
console.log(response.data);
// ...
},
function (error) {
console.log(error);
// ...
}
)
}
});
</script>

Unable to Pass Variable from controller to service in AngularJS

I'm trying to pass a zip code to a service that runs an API call using this zip. The problem is, every time I enter a zip and search, the zip code is not passed to the service properly and my HTTP request sends with the zip code as undefined.
Here is my controller:
angular.module('MainCtrl', []).controller('MainController', ['$scope', 'Reps', function($scope, Reps) {
$scope.search = function() {
Reps.search($scope.zipCode)
.success(function(response) {
console.log('Success ' + response);
})
.failure(function(response) {
console.log('Failure ' + response);
})
}
}]);
My service:
angular.module('MainService', []).factory('Reps', ['$http', function($http) {
var root = 'https://www.api.com/locate?';
var apiKey = '&apikey=foo';
var fields = '&fields=bar';
return {
search: function(zipCode) {
var query = root + zipCode + apiKey + fields;
return $http({
method: 'POST',
url: query
})
}
}
}])
My form:
<form method="post" enctype="text/plain" class="form-inline">
<div class="form-group">
<label for="searchForRep">Zip Code:</label>
<input type="text" class="form-control" id="searchForRep" ng-model="zipCode" placeholder="Zip Code (11216)">
</div>
<button ui-sref="reps" ng-click="search()" type="submit" class="btn btn-default">Submit</button>
</form>
So, as mentioned, the zip code does not seem to pass to my service correctly, which is causing the HTTP request to send as:
https://www.api.com/locate?undefined&apikey=foo&fields=bar
Any idea what the issue is with my code?
As per your code it should work. It is working on my plunker, except you did not add your service module to your controller module like:
angular.module('MainCtrl', ['MainService']).controller('MainController',
Plunker here: http://plnkr.co/edit/Ey3K5eF5h56dqWTji5uX?p=preview

Form data always going null for text field in angular js and rest service spring

I am new to AngularJS and not sure where I am missing, though I know its a minor mistake which I am committing. Please help me out with below scenario.
I have a form where in I write a post {textArea} and click submit button, which calls ng-click=createPost() method.
It goes to controller.js which is:
app.controller('MyCtrl1', ['$scope', 'PostFactory', '$location', function ($scope, PostFactory, $location) {
/* callback for ng-click 'createUser': */
$scope.createPost = function() {
alert("in createPost" + $scope.post.postText);
alert("in createPost" + $scope.post);
PostFactory.create($scope.post)
$scope.posts.push($scope.post.postText);
$scope.post = "";
$location.path('/view1');
}
$scope.posts = PostFactory.query();
/*UserFactory.get({}, function (userFactory) {
$scope.firstname = userFactory.firstName;
})*/
}]);
and my service.js is:
var services = angular.module('ngdemo.services', ['ngResource']);
//alert("In services");
services.factory('PostFactory', function ($resource) {
// alert("Reached services.js");
return $resource('/ngdemo/web/posts', {}, {
query: {
method: 'GET',
//params: {},
isArray: true
},
create: {method: 'POST'}
})
});
my Spring controller which is exposed as service and have post method:
#RequestMapping(/*value = "/add",*/ method = RequestMethod.POST)
public #ResponseBody String addPost(#ModelAttribute(value = "") Post post, BindingResult result) {
System.out.println("Post value : " + post.getPostText());
//post.setPostId();
post.setPostTags("#dummy");
postService.addPost(post);
return "redirect:/";
}
my form :
<form novalidate="novalidate" class="form-horizontal">
<!-- Textarea -->
<div class="form-group">
<div class="col-md-4">
<textarea ng-model="post.postText" rows="4" cols="300" name="inputQuestion" id="post.postText" class="form-control expand" placeholder="What you want to pingle today?"></textarea>
</div>
<br>
<!-- Button -->
<div class="col-md-4">
<button ng-click='createPost()' class="btn btn-default plus"> Pingle it! </button>
</div>
</div>
</form>
Problem is : always Post value in controller is coming as null, have tried with $scope.post and $scope.postText but no joy!
Please let me know where I am missing?????
UPDATE:
How can we pass a form object to Spring Controller in controller.js?? Post is my Domain object
it worked, once I replaced #ModelAttribute with #RequestBody, somehow it was preventing the data to be populated in my object. After setting #RequestBody, it worked!Thanks all!

Resources