AngularJS - get label text for field - angularjs

Question
I was wondering what the AngularJS "best practice" way of getting a label for a field is. With jQuery you just query using a "label for" query then extract the text. While it's possible to do it this way with AngularJS, something just doesn't feel right about it.
Assume you have something like this in your HTML:
<form name="MyForm" ng-controller="Ctrl">
<label for="MyField">My spoon is too big:</label>
<input type="text" size="40" id="MyField" ng-model="myField" />
<br /><br />
You entered {{ myField }} for {{ myField.label }}
</form>
The controller internal is pretty simple:
$scope.myField = 'I am a banana.';
Basically I want to populate the myField.label in the output with "My spoon is too big."
What I'm Doing Now
All I am doing right now is executing a query that pulls the data similar to the jQuery methodology ($("label[for='MyField']")). Then, if that doesn't exist I am just pulling the placeholder text. It works, but it seems like a bit of overhead.
What I'm Trying to Accomplish
I want some custom form validation and I want to include the label in the message. I just need to pull the label text so that I can write it extremely generically and then not have to worry about people switching i18n data in dynamically later in the game.
Fiddle
Per the suggested solution:
https://jsfiddle.net/rcy63v7t/7/

You change your HTML to the following:
<label for="MyField">{{ myFieldLabel }}</label>
<input type="text" size="40" id="MyField" ng-model="myField" />
and your JS to the following:
$scope.myFieldLabel = 'My spoon is too big:';
then later, you can get/set its value just as easily:
if ($scope.myFieldLabel === 'My spoon is too big:') {
$scope.myFieldLabel = 'New label:';
}
Note that new AngularJS best practices call for always using a "dot" in a field reference. It would fit perfectly here if you did something like:
<label for="MyField">{{ myField.label }}</label>
<input type="text" size="40" id="MyField" ng-model="myField.value" />
and JS:
$scope.myField = {
value: '',
label: 'My spoon is too big:'
};
Then you can always easily access $scope.myField.label and $scope.myField.value.

Let's say in your controller you have a scope variable like
$scope.myField = {};
$scope.myField.label = "Fruit name";
and your template is like
<form name="MyForm" ng-controller="Ctrl">
<label for="MyField">{{myField.label}}</label>
<input type="text" size="40" id="MyField" ng-model="myField.value" />
<br /><br />
You entered {{ myField.label }} for {{ myField.label }}
</form>
By this field label will come dynamically. Apply custom validation in input field as per your requirement.
Hope I understand exactly what you wants.

Just put your label text in the input title and you can use a "#" directive. You can also use this to make sure the label id matches.
<label for="{{myfield_control.id}}">{{myfield_control.title}}</label>
<input type="text" size="40" id="MyField" ng-model="myField" title="My spoon is too big:" #myfield_control >
<br /><br />
You entered {{ myField }} for {{ myfield_control.title }}
myField is your ngModel. myfield_control is a reference to your input control.

Related

Elegant solution for a dynamic ng-repeat form

I am new to AngularJS and I have following problem:
I want to iterate over an array of 'attributes' with a bunch of keys for the values stored in the Object.
<div ng-repeat="key in attributes">
{{key}}: <input type="text" value={{Object.key}} name="{{key}}">
</div>
This code displays just the correct key of {{column}} but delivers no result for the value of {{Object.column}}.
The phrase {{Object.{{column}}}} dosn't work neither.
If I run the code, giving the Object a static key of (e.g. ID) everything works perfectly.
I could go for
<div>
id: <input type="text" value={{Object.id}} name="id">
name: <input type="text" value={{Object.name}} name="name">
value: <input type="text" value={{Object.value}} name="value">
and so on...
</div>
But this static form does not seem to be the perfect solution.
Can someone help me?
You should do something like this -
<div ng-repeat="key in attributes">
{{key}}: <input type="text" value={{ Object[key] }} name="{{ Object[key] }}">
</div>
Use {{Object[key]}}. Angular considers .key to be a constant not a variable.

AngularJS - how to sync result of calculated input field to a scope variable

I'm trying to sync the result of a calculated form field into a scope variable. For example:
<div class="form-group">
<label for="val1" class="control-label">Val 1</label>
<input class="form-control" name="val1" type="number" ng-model="data.val1" id="val1">
</div>
<div class="form-group">
<label for="val2" class="control-label">Val 2</label>
<input class="form-control" name="val2" type="number" ng-model="data.val2" id="val2">
</div>
<div class="form-group">
<label for="score" class="control-label">Score</label>
<input class="form-control" name="score" value="{{data.val1+data.val2}}" type="text" id="score">
</div>
<br/>data: {{data}}
How can I sync the result (i.e. the score field) into the scope variable $scope.data.score? I have tried ng-model="data.score" but that breaks the calculation.
You can see the example in action here:
http://plnkr.co/edit/fc9XcyyYGtAk0aGVV35t?p=preview
How do I get the last line to read data: {"val1":1,"val2":2,"score":3}?
Note that I'm looking for a solution that involves minimal to no code support at the controller level. For example, I know you can set up a watch in the controller for both val1 and val2 and then update the score in the watcher. This is what I wanted to avoid, if it's possible in angular at all. If it's not (theoretically) possible, I'd really appreciate an explanation of why it's not.
A quick background might help. Basically we have a simple form builder app that defines a form and all its fields in an xml file. Here's a sample of what the xml would look like:
<form name="test">
<field name="val1" control="textbox" datatype="number">
<label>Val 1</label>
</field>
<field name="val2" control="textbox" datatype="number">
<label>Val 2</label>
</field>
<field name="score" control="textbox" datatype="number">
<label>Score</label>
<calculate>[val1]+[val2]</calculate>
</field>
</form>
When a form is requested, the system will need to pick up the xml, loop through all the fields and generate an angular style html to be served to the browser and processed by angular. Ideally, I want to keep all the form specific logic (validation, show/hide, calculation etc) confined to the html, and keep the controller (js) logic generic for all forms.
The only solution I can come up with is to dynamically load watcher functions, through something like this: eval("$scope.$watch('[data.val1,data.val2]')..."), but as I said, I really want to avoid this, because it's just tedious, and feels extremely dodgy :)
The first dirty way.
In your case you can move all logic from controller into html with using combination of ng-init and ng-change directives.
<div class="form-group">
<label for="val1" class="control-label">Val 1</label>
<input class="form-control" name="val1" type="number" ng-model="data.val1" ng-change="data.score = data.val1 + data.val2" id="val1">
</div>
<div class="form-group">
<label for="val2" class="control-label">Val 2</label>
<input class="form-control" name="val2" type="number" ng-model="data.val2" ng-change="data.score = data.val1 + data.val2" id="val2">
</div>
<div class="form-group" ng-init="data.score = data.val1 + data.val2">
<label for="score" class="control-label">Score</label>
<input class="form-control" name="score" ng-model="data.score" type="text" id="score">
</div>
<br/>data: {{data}}
I don't think that it's the clearest solution, but you can leave your controller without any changes with it.
Demo on plunker.
The second dirty way.
There is one more way, but now you don't need ng-init and ng-change directives. You can add just one dirty expression in html:
<div id="main-container" class="container" style="width:100%" ng-controller="MainController">
{{data.score = data.val1 + data.val2;""}} <!-- key point -->
<div class="form-group">
<label for="val1" class="control-label">Val 1</label>
<input class="form-control" name="val1" type="number" ng-model="data.val1" id="val1">
</div>
<div class="form-group">
<label for="val2" class="control-label">Val 2</label>
<input class="form-control" name="val2" type="number" ng-model="data.val2" id="val2">
</div>
<div class="form-group">
<label for="score" class="control-label">Score</label>
<input class="form-control" name="score" ng-model="data.score" type="text" id="score">
</div>
<br/>data: {{data}}
;"" in expression stops evaluating of angular expression to text in html.
Demo on plunker.
See if this works, in your HTML change,
<input class="form-control" name="score" ng-model = "data.score" type="text" id="score">
and, in your controller do,
var myApp = angular.module('myapp', [])
.controller('MainController', function($scope) {
$scope.data = { val1: 1, val2: 2, score: 3};
$scope.$watch('[data.val1,data.val2]', function (newValue, oldValue) {
$scope.data.score = newValue[0] + newValue[1];
}, true);
})
Demo plunk, http://plnkr.co/edit/gS0UenjydgId4H5HwSjL?p=preview
If you want to know how you can do it, then i have one solution for you make a ng-change event for both of your text box and sum both the number there and use ng-model in the third text box then, you can see it will work as per your need.
For the first time load you need to calculate it out side only.

Angular form validation using the controllerAs syntax

I am currently facing the following problem:
I would like to validate my form input using the Angular ngModel directives.
When using those together with $scope they work fine.
Now, working with the controllerAs syntax, they fail to work.
This problem is poorly documented, the only help I could find is this article.
Here is a small example of my code:
The template gets called with myController as vm
<form name="vm.signUpForm" ng-submit="vm.signup(vm.user)">
<label for="name">Name</label>
<input type="text"
class="form-control"
id="name"
name="name"
placeholder="Full name"
ng-model="vm.user.name"
ng-minlength="2" required />
<div ng-show="vm.signUpForm.$submitted || vm.signUpForm.name.$touched">
<span ng-show="vm.signUpForm.name.$error.required">Please fill in your name</span>
<span ng-show="vm.signUpForm.name.$error.minlength">A minimum of 2 [...]</span>
</div>
[...]
</form>
Am I forced to use $scope to validate the form? Or did I miss something ?
Thanks in advance!
Solution by: Andrew Gray
I had to change the following lines to get this to work:
<form name="vm.signUpForm" ... >
<!-- To -->
<form name="signUpForm" ...>
<div ng-show="vm.signUpForm.$submitted || vm.signUpForm.name.$touched">
<!-- To -->
<div ng-if="signUpForm.name.$invalid">
<span ng-show="vm.signUpForm.name.$error.required" ... >
<!-- To -->
<span ng-show="signUpForm.name.$error.required" ... >
First things first - you don't need the vm. on the form.
<form novalidate name="someForm">
<label>
Some Text:
<span class="danger-text" ng-if="someForm.someText.$invalid">
ERROR!
</span>
</label>
<input type="text" name="someField" />
</form>
The way it winds up working, is that there's a validation object that is not tied to the scope. The controllerAs syntax is just spinning off a instance of the controller as a scope variable.
Try shaving off the vm. from the form and child elements' names, and you should be OK.

angularjs form with ng-options

I'm having trouble with a form using angularjs/php/mysql to make a quite simple CRUD.
My form pass correctly the text inputs but I can't pass the <select> value.
The ng-option expression below is wrong but I can't find how to write it.
<div ng-controller="formController">
<form ng-submit="addVinyl()" novalidate class="simple-form">
Owner: <select ng-model="vinyl.owner" ng-options="user.name for user in users"></select><br />
Title: <input type="text" ng-model="vinyl.name" /><br />
Artist: <input type="text" ng-model="vinyl.artist" /><br />
<input type="submit" value="Add Vinyl" />
</form>
</div>
gives this html:
<option value="0">hey</option>
<option value="1">hoy</option>
<option value="2">hay</option>
My php file gets the good values of the text inputs but doesn't get the '0', '1', '2' or the 'hey', 'hoy', 'hay'... I tried to display vinyl.ownerand I got {"NAME":"hey"} for the first option selected.
ng-options is not the same as ng-repeat
The correct syntax for your purpose is :
ng-options="user.name as user.name for user in users"
This is due to the fact that you need a value for the attribute value, and that you need a "display text".
find more information inside documentation :
https://docs.angularjs.org/api/ng/directive/ngOptions

Translated form validation in AngularJS

What's the easiest way of changing the default error messages in form validation provided by Angular to another language?
If I'm not mistaken, you think about html5 validation.
Something like this:
<b>HTML5 validation</b>
<form>
First name:
<input type="text" name="firstName" required="" />
<br />
Last name:
<input type="text" name="lastName" required="" />
<br />
<input type="submit" value="Submit" />
</form>
If user click on the Submit button he will see:
I think that this error comment you cannot change because it depends on the user browser/computer settings.
Maybe you should try to use angularjs validation (first add to form novalidate to switch off HTML5 validation):
HTML
<div ng-controller="PersonController">
<b>AngularJS validation</b>
<form novalidate name="myForm">
First name:
<input type="text" name="firstName" ng-model="newPerson.firstName" required="" />
<span style="color: red" ng-show="myForm.firstName.$dirty && myForm.firstName.$invalid">First name is required</span>
<br />
Last name:
<input type="text" name="lastName" ng-model="newPerson.lastName" required="" />
<span style="color: red" ng-show="myForm.lastName.$dirty && myForm.lastName.$invalid">Last name is required</span>
<br />
<button ng-click="resetPerson()">Reset</button>
<button ng-click="addPerson()" ng-disabled="myForm.$invalid">Save</button>
</form>
</div>
JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('PersonController', ['$scope',
function($scope) {
var emptyPerson = {
firstName: null,
lastName: null
};
$scope.addPerson = function() {
alert('New person added ' + $scope.newPerson.firstName + ' ' + $scope.newPerson.lastName);
$scope.resetAdvert();
};
$scope.resetPerson = function() {
$scope.newPerson = angular.copy(emptyPerson);
// I don't know why not work in plunker
//$scope.myForm.$setPristine();
};
$scope.resetPerson();
}
]);
If user fill the field and erase he will see the error info:
The submit button will be disabled if user don't fill the required fields.
Plunker example
Why don't you try something easy for a change... :) Well here is my Angular-Validation. I made a project on Github and I think you can't be simpler than that...and yes I also support translation localization, those are saved into an external JSON file:
<!-- example 1 -->
<label for="input1">Simle Integer</label>
<input type="text" name="input1" validation="integer|required" ng-model="form1.input1" />
<span class="validation text-danger"></span>
<!-- example 2 -->
<label for="input2">Alphanumeric + Exact(3) + required</label>
<input type="text" name="input2" validation="alpha|exact_len:3|required" ng-model="form1.input2" />
<span class="validation text-danger"></span>
JSON external file for translation locales
// English version, JSON file (en.json)
{
"INVALID_ALPHA": "May only contain letters. ",
"INVALID_ALPHA_SPACE": "May only contain letters and spaces. ",
...
}
// French version, JSON file (fr.json)
{
"INVALID_ALPHA": "Ne doit contenir que des lettres. ",
"INVALID_ALPHA_SPACE": "Ne doit contenir que des lettres et espaces. ",
...
}
On top of supporting multiple translations, the directive is so crazy simple for validation, that you'll just love it. I can define whatever amount of validation rules (already 25+ type of validators available) under 1 attribute. validation="min_len:2|max_len:10|required|integer" and the error message will always be displayed in the following <span> isn't it beautiful? I think so too hehe... 1 line of code for your input, 1 line of code for the error display, can you beat that? oh and I even support your custom Regex if you want to add. Another bonus, I also support whichever trigger event you want, most common are probably onblur and onkeyup. I really added all the imaginable features I wanted into 1 crazy simple directive.
No more clustered Form with 10 lines of code for 1 input (sorry but always found that ridiculous) when the only little piece you need is 2 lines of code, nothing more, even for an input of 5 validators on it. And no worries about the form not becoming invalid, I took care of that as well, it's all handled the good "Angular" way.
Take a look at my Github project Angular-Validation... I'm sure you'll love it =)
DEMO
Added a live demo on Plunker

Resources