Upload image within ng-submit form - angularjs

I'm new to Angular.js and I would like to know how to upload an image within my ng-submit form. It works perfectly for the next based fields but with the file it only gives me the 'choose file' button without displaying it after hitting the submit button.
<form ng-submit="addartikel()">
<input type="text" placeholder="Bezeichnung" ng-model="newartikel.name" />
<input type="text" placeholder="Kategorie" ng-model="newartikel.kategorie" />
<input type="text" placeholder="Preis" ng-model="newartikel.preis" />
<input type="file" placeholder="Bild" ng-model="newartikel.thumb" />
<input type="submit" value="Artikel hinzufügen" />
As for the controller:
webShop.controller('InventarController', ['$scope', '$http', function($scope, $http){
$scope.addartikel = function(){
$scope.inventar.push({
name: $scope.newartikel.name,
kategorie: $scope.newartikel.kategorie,
preis: parseInt($scope.newartikel.preis),
thumb: $scope.newartikel.thumb,
available: true
});
Your help would be greatly appreciated :)

Use Angular File Upload.It is available in https://github.com/nervgh/angular-file-upload

Related

How to reset validation after submitting a form in AngularJS?

I have one input field:
<input type="text" name="title" ng-model="genreData.title" class="form-control"
ng-class="{'error': addGenreForm.title.$invalid && !addGenreForm.title.$pristine}"
placeholder="Genre name" ng-minlength="minlength" required autofocus>
When I succesfully submit form this input is got class="error" after this:
$scope.genreData = {};
How can I fix it?
You've got to inject the form in the ng-submit function and then call the form's controller built in function $setPristine().
e.g.
View:
<form name="myForm" ng-submit="submitForm(myForm)">
<!--Input Fields-->
</form>
Controller:
$scope.submitForm = function(form) {
//Do what ever I have to do
//Then reset form
form.$setPristine();
}
I think setting
$scope.addGenreForm.$setPristine() and $scope.addGenreForm.$setUntouched
can work after submitting your form
Please share some plunker so I can help more if you still have any issues

js form submit is not working

I am trying to submit a form, but the values are always empty.
my HTML:
<form novalidate name="creditCardForm" id="creditCardForm" method="POST">
<input type="hidden" name="EPS_MERCHANT" value="{{credit.data.merchantId}}">
<input type="hidden" name="EPS_TIMESTAMP" value="{{credit.data.currentGMTTimestamp}}">
<input type="hidden" name="EPS_TYPE" value="{{credit.data.epsType}}">
<div class="text-center">
<button class="btn btn-primary" ng-click="credit.save()">Save</button>
</div>
</form>
and my js part:
function save(){
document.getElementById("creditCardForm").setAttribute("action", this.data.crnUrl)
document.forms["creditCardForm"].submit()
}
and from inspection, these fields all have values
but from the request, these fields are all empty:
update my question:
because this is a special form post that it will call NAB bank api to verify something, so I cannot put each fields into an object and do a ajax/$resource/$http call.
thanks
That's a not angular way to submit the form via action attribute. Use ng-submit form attribute and make a $http.post request async.
<form novalidate name="creditCardForm" id="creditCardForm"
ng-submit="saveCredit(creditCardForm)">
<!-- no input hidden -->
<div class="text-center">
<button class="btn btn-primary">Save</button>
</div>
</form>
And you dont need hidden inputs in this way.
If I get your question and your requirement correct. You should be using following way:
<form novalidate name="creditCardForm" id="creditCardForm" method="POST">
<input type="hidden" name="EPS_MERCHANT" ng-model="credit.data.merchantId">
<input type="hidden" name="EPS_TIMESTAMP" ng-model="credit.data.currentGMTTimestamp">
<input type="hidden" name="EPS_TYPE" ng-model="credit.data.epsType">
<div class="text-center">
<button class="btn btn-primary" ng-click="credit.save(credit.data)">Save</button>
</div>
</form>
This is assuming that credit is the alias for your controller.
I have tried to keep your ways of ng-click to call a method on controller. However with forms in angular, you can do the same via ng-submit directive also.
In your controller you will have something like:
$scope.save = function(data){
//use data here as you like
//data.merchantId and other fields
}
If you are using alias form, then use:
//vm or any other name you have for your `this` instance
vm.save = function(){
// use data here as you like
}
I want to try to fix your problem. The first thing that you have to do is add ng-model and ng-value in your form. For example:
view:
<form novalidate name="creditCardForm" id="creditCardForm" ng-submit="save()">
<input type="hidden" ng-model="credit_card.eps_merchant" name="eps_timestamp" ng-value="{{credit.data.merchantId}}">
<input type="hidden" ng-model="credit_card.eps_timestamp" name="eps_timestamp" ng-value="{{credit.data.currentGMTTimestamp}}">
<input type="hidden" ng-model="credit_card.eps_type" name="eps_type" ng-value="{{credit.data.epsType}}">
<div class="text-center">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
For the next you can create controller. For example:
angular controller:
angular.module('cartApp')
.controller('AddCreditCartCtrl', [
'$scope',
'$location',
'$http',
function($scope, $location, $http) {
$scope.credit_card = {};
$scope.credit.data = {
merchantId: 'your-merchant-id',
currentGMTTimestamp: 'your-currentGMTTimestamp',
epsType: 'your-epsType'
}
$scope.save = function () {
$http.post('/yourUrl', {credit_card: $scope.credit_card}).then(function(res){
// Successfully create data
},
function(response) {
// Failed to create data
});
}
}]);
I hope this can help you. :)
thanks every body above. just want to share the root cause
I have a directive called <credit-card></credit-card>, and inside this directive, I have the form, with both name and id to be creditCardForm, so when this directive is used in several places, and in the controller I use document.forms["creditCardForm"], js did not know which is the target form, and this results in empty values in the request
hope it can help someone with same problem

Scope inheritance with ng-bind (not working) vs {{ }} (working)

I am learning AngularJS and just done with the scope inheritance. Following is the sample code I wrote. I am referencing angular version 1.5.0
HTML
<div ng-controller="ScopeInheritanceParentController" class="scope_inheritance_parent">
<span>Parent</span><br /><br />
<!--<span ng-bind="title" /><br /><br />-->
<span>{{title}}</span><br /><br />
<input type="text" ng-model="title" /><br /><br />
<div ng-controller="ScopeInheritanceChildController" class="scope_inheritance_child">
<span>Child</span><br /><br />
<!--<span ng-bind="title" /><br /><br />-->
<span>{{title}}</span><br /><br />
<input type="text" ng-model="title" />
</div>
</div>
JS
angular.module('myapp.controllers')
.controller('ScopeInheritanceParentController', ['$scope', function ($scope) {
$scope.title = "Initial title set by Parent controller ctor function"
}])
.controller('ScopeInheritanceChildController', ['$scope', function ($scope) {
$scope.title = 'Initial title set by Child controller ctor function'
}])
So far so good and I get the output as:
Issue
When I comment {{title}} syntax and uncomment ng-bind="title" span I see the output as:
Where is Child controller now?
Why is it not displaying text box from Parent controller?
I know that {{}} syntax creates a watcher internally and thus angular is able to update view when expression changes. I also read that ng-bind is same as {{}}, so I would assume it works the same way.
span tag has such syntax
<span ng-bind='title'></span>

Clearing all inputs and restoring .ng-pristine on click

It's still the first day of me using AngularJS after inheriting the project from a fellow developer. I was wondering, I have a login/registration form on my interface that is hidden once the items/form is submitted. Now once the user has submitted is there a correct or proper way to clear the form of it's entries and restore the .ng-pristine class on the items. The reason for this is should the user choose to log out and then login again (or another user wishes to register) the form is populated and has the validation css applied to it already. I don't want this, I would want everything to be empty and no CSS applied.
I can do this in JavaScript (obviously) however with AngularJS being a different approach I was wondering if I should approach this issue another way rather than loop through the form items and append a class to each item whilst clearing it's value.
This an example of one of my forms
<form name="signupForm" novalidate ng-submit="register(user)">
<div><label for="email">email:</label><input type="email" id="email" name="email" required ng-model="user.email" ng-minlength=4></div>
<div><label for="userName">Username:</label><input type="text" name="userName" id="userName" ng-model="user.userName" required ng-pattern="/^[A-Za-z0-9 \-_.]*$/" ng-minlength=4></div>
<div><label for="firstName">Vorname:</label><input type="text" name="firstName" id="firstName" ng-model="user.firstName" required ng-pattern="/^[A-Za-z \-_.]*$/" ng-minlength=3></div>
<div><label for="lastName">Nachname:</label><input type="text" name="lastName" id="lastName" ng-model="user.lastName" required ng-pattern="/^[A-Za-z \-_.]*$/" ng-minlength=4></div>
<div><label for="password1">Passwort:</label><input type="password" name="password1" id="password1" ng-model="user.password1" required ng-minlength=4></div>
<div><label for="password2">Passwort wiederholen:</label><input type="password" name="password2" id="password2" ng-model="user.password2" valid-password2 ng-minlength=4 pw-check="password1"></div>
... and so on
Many thanks
The form will appear in the correct scope under its name, i.e. $scope.signupForm. Additionally the object populating the form is $scope.user. In your controller, do:
$scope.user = {}; // or new User() if it is your case
$scope.signupForm.$setPristine();
In case $scope.signupForm is undefined, put a controller directly on the form, and place the code above (and anything else applicable) inside this new controller:
<form name="signupForm" novalidate ng-submit="register(user)"
ng-controller="NewCtrl">
(This may happen due to scope nesting under your original controller.)
Just refer to this post :
Reset form to pristine state (AngularJS 1.0.x)
In the main question you got reference to issues and pull request on AngularJS. In resume you have to use $setPristine() method to your form.
Hope it helps !
var app = angular.module('App', []);
app.controller('formController', function($scope, $document){
$scope.Clear = function(){
angular.forEach(angular.element($document[0].querySelectorAll('input[type=text], input[type=email], input[type=password]')), function (elem, index) {
elem.value = '';
/*
Just extra do something
elem.parent().parent().removeClass('has-error has-success');
elem.parent().parent().children().find('span').removeClass('glyphicon-exclamation-sign glyphicon-ok');
*/
});
$scope.myForm.$setPristine();
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
</head>
<body ng-app="App">
<div ng-controller="formController">
<form name="myForm">
<input type="text" name="FirstName" ng-model="FN"/> <br>
<input type="text" name="LastName"/>
<br>
<input type="text" name="UserName"/>
<br>
<input type="password" name="Password"/>
</form>
<button ng-click="Clear()">Clear</button>
</div>
</body>
</html>
Here is my Example, it worked for me i am using angularjs 1.6

Angular JS Forms submit not sending model data

In the following example, message is undefined when I display it in the controller after the event is fired. Why?
<form>
<input type="text" ng-model="message.Title" />
<textarea ng-model="message.Content"></textarea>
<input type="submit" value="Send Message" ng-click="sendMessage(message)" />
</form>
Controller:
$scope.sendMessage = function(message) {
console.log(message);
}
My code seems identical to the documentation here except my controller manages the entire "page" not just the form.
Wow nevermind, apparently when you submit with blank values it doesn't even create the object.
I see you've found your problem, but I'd like to propose a solution to prevent your problem anyway:
<form name="messageForm" ng-submit="sendMessage(message)">
<input type="text" ng-model="message.Title" required/>
<span ng-show="messageForm.title.$error.required && messageForm.title.$dirty">required</span><br/>
<textarea ng-model="message.Content"></textarea>
<input type="submit" value="Send Message" ng-disabled="messageForm.$invalid" />
</form>
The above will make the Title required, display an error message, and disable your submit button if the form isn't valid.

Resources