How get AngularJS element by name? - angularjs

In my form validation there is part of server validations.
So I should get back from the server list with the names of the fields and a string with the error in each of them.
My idea was to write a general code knowledge to deal with all fields without knowing them in advance, by accessing them with their name.
this is field for example:
<!-- Email -->
<div class="form-group" data-ng-class="{ 'has-error' : step1Form.email.$invalid && (!step1Form.email.$pristine || submitted) }">
<label>Email</label>
<input type="email" name="email" class="form-control" data-ng-model="user.email" required data-ng-minlength="5" data-ng-maxlength="60">
<p data-ng-show="step1Form.email.$error.required && (!step1Form.email.$pristine || submitted)" class="help-block">required!</p>
<p data-ng-show="step1Form.email.$error.minlength" class="help-block">too short1</p>
<p data-ng-show="step1Form.email.$error.maxlength" class="help-block">too long!</p>
<p data-ng-show="step1Form.email.$error.email" class="help-block">invalid email!</p>
<p data-ng-show="step1Form.email.$error.serverError" class="help-block">{{emailServerError}}</p>
</div>
like you can see, the variable emailServerError is saved for errors that come from the server validations...
i have a lot fields in my application and i try to write generic code that will fit for all the fields...
so this is the angular code:
// function to submit the form after all validation has occurred
$scope.submitForm = function() {
// check to make sure the form is completely valid
if ($scope.step1Form.$valid) {
// now we will go to server side validation
// AJAX calls.......
// lets say we got this back:
var problem = { field: 'email', msg: 'this email is already registered'};
// now we need to setValidity for email input.
var errorVariableName = $parse(problem.field + 'ServerError'); // Get the name of the error string variable.
errorVariableName.assign($scope, problem.msg); // Assigns a value to it
console.log($scope.emailServerError); // = 'this email is already registered'
// HERE THE PROBLEM:
// now i need to do something like that:
// $scope.step1Form. + problem.field + .$setValidity('serverError', false);
// but i dont know how to this that.
// i think that i need to get this element ($scope.step1Form. + problem.field) in some way by name, and then use setValidity on it. but i dont know how..
}
};
the question is in the comments inside the code...

You can try
$scope.step1Form
and then access the right value with
$scope.step1Form["nameOfProblemfield"]

Related

AngularJS doesnt show the value of object's property

this should be straight forward, just cant figure out why it's not working.
I receive data in this format from Web API 2 (captured from Chrome's debugger):
AngularJS code to render the results
(vm.reportParameters contains that structure on the screenshot with 2 nodes):
<form>
<div ng-repeat="param in vm.reportParameters" class="form-group">
<label>Name</label>
<input type="text" class="form-control" value="{{param.Name}}" />
</div>
</form>
The output (missing value of Name property, should display "Country"):
Any idea what I am missing here? Why the value is not shown?
// GET api/reports/5
// This action retrieves parameters of selected report by reportId
[ResponseType(typeof(ParametersModel))]
public IHttpActionResult Get(string reportId)
{
try
{
var manager = new ReportsManager();
var model = manager.GetReportParameters(reportId);
if (model == null || model.Parameters == null || model.Parameters.Count == 0)
{
return NotFound();
}
return Ok<ParametersModel>(model);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
Thanks.
UPDATE
This garbage-alike data has this weird format with all these k__XXXXX
things because I had various attributes applied to the model for XML
Deserialization (in C# code). After I removed all these Serialization
attributes, the model became normal and clean as expected. Go guess :)
Use without expression, ng-model
<input type="text" class="form-control" ng-model="param.Name" />

Post full form data to a service in Angular

I have a form that contains a lot of fields and I want to post all the form fields to a service using a post method. But I would like to send the whole form object and not to write one property by one. If I try to post the object that contains all my fields $scope.formData it also contains all the angular stuff inside like errors. What I need is a collection of field names and values. How can I achieve this with minimum coding?
Edit:
I ended up writing my own function:
function getAngularFormFields(form) {
var dictionary = { form: {} };
for (var key in form) {
if (form.hasOwnProperty(key) && !key.indexOf('$') == 0) {
dictionary.form[key] = form[key].$modelValue;
}
}
return dictionary;
}
Normally if you need to post a form you could just use the default method provided by your browser. This will send the form data, via POST, to your URL.
<form action="yourUrlHere" method="POST">
First name: <input type="text" name="fname">
Last name: <input type="text" name="lname">
<input type="submit" value="Submit">
</form>

Show Validation Summary in AngularJS on Form Submit

Is it possible to show a Validation Summary, a Div on top of the page with all the Validation error messages in angularjs , on form submit ?
I am coming from a .Net background and used to have a validation summary concept,all the examples i have seen in angular shows the error message right next to the control.
I am very new to angularjs , so an example or pointer to the right direction would be appreciated !
Thanks !
Yeah, you can use flags on each of your input fields, which will show a specific error message based on whether that flag is true or false.
For example:
<div ng-controller="signupCtrl">
<input type="text" id="username">
<input type="text" id="password">
<button ng-click="validate()">Sign-up</button>
</div>
Then, the validate function would run several other functions that would set flags. For example:
function signupCtrl($scope) {
$scope.validate = function() {
if( /* username is bad */ ) {
$scope.usernameError = true;
} else if ( /* password is bad */ ) {
$scope.passwordError = true;
} else {
// AJAX call to submit sign-up, or whatever
}
}
}
Your error messages would look like this:
<div class="error" ng-show="usernameError">Your username is bad</div>
<div class="error" ng-show="passwordError">Your password is bad</div>
Or, better yet, you can use a model, and only one error message:
<div class="error" ng-show="error">You {{field}} is bad</div>
But that second option would require some different tweaking of your code.

AngularJs form validation - manage custom errors priority to show only one error with the ng-show directives

here is my first question on this awesome forum.
my need is to warn the user why the number he enters is invalid, but I want to print only one message at each time. I've implemented a solution but it's not really easily evolutive.
Here is my HTML code :
<input type="number" name="amountReceived" class="styled" data-ng-model="cashAmountReceived" required>
<div class="error" data-ng-show="cashPaymentForm.amountReceived.$error.required && cashPaymentForm.submitted">Valid amount required</div>
<div class="error" data-ng-show="cashPaymentForm.amountReceived.$error.notEnought && cashPaymentForm.submitted">It's not enought</div>
<div class="error" data-ng-show="cashPaymentForm.amountReceived.$error.negatif && cashPaymentForm.submitted">Positive value only</div>
and here is my Controller code :
$scope.$watch('cashAmountReceived', function() {
if(angular.isNumber($scope.cashAmountReceived)){
var tmp = $scope.cashAmountReceived.toString();
tmp = tmp.replace(/(\d{0,9})+\.(\d{0,2}).*/,'$1.$2');
$scope.cashAmountReceived = parseFloat(tmp);
if( $scope.cashAmountReceived < 0){
$scope.cashPaymentForm.amountReceived.$setValidity('negatif', false);
$scope.cashPaymentForm.amountReceived.$setValidity('notEnought', true);
}
else{
$scope.cashPaymentForm.amountReceived.$setValidity('negatif', true);
if($scope.cashAmountReceived < $scope.totalProductPrice){
$scope.cashPaymentForm.amountReceived.$setValidity('notEnought', false);
}
else{
$scope.cashPaymentForm.amountReceived.$setValidity('notEnought', true);
}
}
}
else{
$scope.cashPaymentForm.amountReceived.$setValidity('notEnought', true);
$scope.cashPaymentForm.amountReceived.$setValidity('negatif', true);
}
});
I've to manually manage validity errors to make sure that only one will be printed thanks to the ng-show directives in my HTML page. I'd like to implement a easily evolutive solution, in case I need to add more validation criteria.
I think about to make my own directive with a priority management system on my custom errors and compatible with the defaults errors possibilities, but I don't know how to proceed.
Or maybe I can leave the process in the controller and create only one custom error called custom and define a scope variable called errorReason whitch will contain the appropriate warning message
I'll have something like that in my HTML code :
<input type="number" name="amountReceived" class="styled" data-ng-model="cashAmountReceived" required>
<div class="error" data-ng-show="cashPaymentForm.amountReceived.$error.custom && cashPaymentForm.submitted">{{errorReason}}</div>
What do you guys think about it?
I apologize if my english is not correct.

ng repeat not updating

Hi I am a newbie to angular js and I am hoping someone can help me out with the following problem.
I have a numeric field called numAdults and I need to show a set of field (such as name, address, telephone etc ) numAdult times to get those information for each of those person.
Here is the jsfiddle for the problem jsfiddle link
Here is also an overview of code of the controller
function bookingController($scope){
$scope.numAdults = 1;
$scope.personLoop = function(){
console.log('personLoop called')
return new Array($scope.numAdults);
//return new Array(2);
}
the html
<label for="book_num_adults">Number of adults:</label>
<input id="book_num_adults" type="text" ng-model="numAdults">
<div class="row" ng-repeat="t in personLoop()" style="border:2px solid red;margin-top:10px">
<h4>Person {{$index+1}}</h4>
<input placeholder="name"><br>
<input placeholder="address"><br>
<input placeholder="telephone"><br>
</div>
Can you also help me with how to transform this as an module ( not just a controller based )
Thank you in advance!
Your Fiddle was riddled with errors...
http://jsfiddle.net/bRgTR/5/
Under Frameworks & Extensions, you need to change the 2nd dropdown from "onLoad" to one of the "No wrap" options
Your controller definition is mangled. It's supposed to be: .controller('name', ['depname', function (depname) { })]); -- you had your closing array misplaced.
You should really use semi-colons.
You don't create an array of 5 items in JavaScript like this: var a = new Array(5), that creates an array that contains a 5. Instead, you should do var a = []; a.length = 5;

Resources