Binding repeatable form subset to model - angularjs

On a registration form I allow a user to enter zero or more phone numbers. Each phone number consists of a prefix and a number, these are two fields per phone number. The user may decide how many numbers he wants to provide, the add more numbers link would clone this part of the form.
Prefix: [_______]
Number: [_______]
+ add more numbers
The model I bind to is fixed and should be this format:
$scope.model = {
"...main inputs": "username, etc...",
phoneNumbers: [
// for each phone number I expect this object
{ "prefix": "+1", "number": "123123123" }
]
};
I am not sure how I should set up my ng-model for these text inputs to have these objects generated within the array.
Also, I am a great fan of referential binding and limiting things like scope watch and event-based changes to the scope, as often these changes go unnoticed for other directives that may be using this value (unless being watched). Basically that means it is my intention to have dynamic generation of objects within the array as the form is filled in with numbers, or dynamic removal of objects within the array as numbers are removed or both inputs left empty.
The array should only contain valid and filled objects, partially filled objects or empty objects should not be added to the model or array (as usually is done with properties with invalid values -- those properties get removed from the model object). Basically a push to the array with every validated object, and removal (slice) of objects for every invalid object. But then rather automatically, instead of writing a push/slice function.

Hi try out this code:
Html:
<form name="form">
<div data-ng-repeat="phone in phoneNumberArray">
<div class="form-group">
<label for="inputFirstName">Prefix</label>
<input id="prefix" class="form-control" type="text" ng-model="phone.prefix">
</div>
<div class="form-group">
<label for="inputLastName">Phone number</label>
<input id="phoneNumber" class="form-control" type="text" ng-model="phone.phoneNumber">
</div>
</div>
</form>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Add more number" data-ng-click="addmore()"/>
</div>
Controller:
$scope.phoneNumberArray = [
{
prefix: "",
phoneNumber:"",
}];
$scope.addmore = function () {
$scope.phoneNumberArray.push({
prefix: "",
phoneNumber: "",
});
}
Hi check this demo in Fiddle

Use the following code.....
<!DOCTYPE html>
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body ng-app ng-controller="todoCtrl">
<form name="form" ng-submit="addmore()">
<div class="form-group">
<label for="inputFirstName">Prefix</label>
<input class="form-control" type="text" ng-model="phone_prefix"/>
</div>
<div class="form-group">
<label for="inputLastName">Phone number</label>
<input class="form-control" type="text" ng-model="phone_Number"/>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Add more number"/>
</div>
</form>
<div ng-repeat="phone in phoneNumberArray">
{{ phone.prefix + " "+ phone.phoneNumber}}
</div>
<script>
function todoCtrl($scope) {
debugger;
$scope.phoneNumberArray = [
{prefix: '14', phoneNumber:'123'}
];
$scope.addmore = function () {
$scope.phoneNumberArray.push(
{prefix: $scope.phone_prefix, phoneNumber: $scope.phone_Number}
);
}
}
</script>
</body>
</html>

Related

get values from each ng-repeat input elements

I have the following code where I have added 5 input texts via ng-repeat and now am trying to fetch each of the input element's values. I am hitting some roadblock, so please help me out on how to fetch individual values.
HTML:
<form class="quick-add-form" method="post">
<label class="quick-add-label">Enter the catalog number and quantity</label>
<div class="quick-add">
<div class="catalog-list">
<label class="catalog-number-label" for="catalog-number-input">Catalog Number:</label>
<div ng-repeat="values in catalogNumber(number) track by $index">
<input id="catalog-number-input-{{$index}}" class="catalog-number-input"
type="text" ng-model="catalog.description" validate-input>
</div>
</div>
<div class="qnty-list">
<label class="pdt-qnty-label" for="pdt-qnty-input">Quantity:</label>
<div ng-repeat="values in catalogNumber(number) track by $index">
<input id="pdt-qnty-input-{{$index}}" class="pdt-qnty-input" type="number" pattern="[0-9]*"
inputmode="numeric" min="1" max="999" ng-model ="catalog.quantity" name="qty"
maxlength="3">
</div>
</div>
</div>
<div>
<button type="submit" class="btn btn-danger cta-button quick-add-btn"
ng-click ="quickAdd(catalog)">Add to List</button>
</div>
</form>
and controller:
$scope.catalog = {};
$scope.catalogNumber = catalogNumber;
$scope.initializeModal = initializeModal;
$scope.quickAdd = quickAdd;
function catalogNumber(num) {
return new Array(num);
}
function quickAdd(val) {
console.log(val);
}
function init() {
$scope.number = 5;
$scope.catalog.quantity = 1;
}
I am pretty sure its because of indexing and which is why by adding value in one input, its adding same value in all at once. But I am not sure how/where to use the $index properly to achieve the result.
Thanks.
Perhaps a better way would be to use the model? For example:
<div ng-repeat="values in catalogNumber(number) track by $index">
<input
id="catalog-number-input-{{$index}}"
class="catalog-number-input"
type="text"
ng-model="catalog.description[$index]"
validate-input>
</div>
Now in your controller:
catalog.description = [];
Then you have an array of objects, which you can perform your math on:
var total = _.sum(Object.values(catalog.description));
Edit: I had forgot I was using Lodash/Underscore there, but if you wanted to use standard JS you could use a standalone method, or reduce etc.,

Basic Save form data the Angular way

I am trying to figure out the "correct" way to get and set form data using Angular. (By "correct" I mean one that supports scalability to larger apps, where controllers aren't overly simple, with shortcut references, as they are in most demos.) When I look though the examples, the seem so basic (such as no controllerAs specifier) that I can't figure out what's pointing at what.
Anyway, I'm expecting that there is an object somewhere in my viewmodel, accessible by the controller, that contains the data in its named fields, suitable for PUTing to the api - and doesn't contain all the cruft that is associated with the actual form and field objects:
To-wit: this is what settingsVm.settingsForm contains:
$dirty:true
$error:{}
$invalid:false
$name:"settingsVm.settingsForm"
$pristine:false
$submitted:true
$valid:true
Email:"asdsa#asdsad.com"
Id:{$validators: {}, $asyncValidators: {}, $parsers: [], $formatters: [], $viewChangeListeners: [],…}
$asyncValidators:{}
$dirty:false
$error:{}
$formatters:[]
$invalid:false
$name:"Id"
$options:null
$parsers:[]
$pristine:true
$touched:false
$untouched:true
$valid:true
$validators:{}
$viewChangeListeners:[]
StreetDirection:""
StreetName:"asdasdsadsada"
StreetNumber:"34"
Suite:""
Here is my form, with just a couple of fields:
<input type="hidden" name="Id" ng-model="settingsVm.settings.Id" />
<div class="form-group row">
<label for="Email" class="col-sm-1 col-form-label text-right"> Email:</label>
<div class="col-sm-5">
<input type="text" class="form-control form-group-med" maxlength="50" name="Email" ng-model="settingsVm.settingsForm.Email" required />
<div class="error-message" ng-show="settingsVm.settingsForm.Email.$invalid && settingsVm.settingsForm.Email.$touched || settingsVm.settingsForm.submitted">
<span ng-show="settingsVm.settingsForm.Email.$error.required"> Email is required.</span >
</div>
</div>
</div>
<div class="form-group row">
<label for="StreetName" class="col-sm-1 col-form-label text-right"> Name:</label>
<div class="col-sm-5">
<input type="text" class="form-control form-group-med" maxlength="50" name="Email" ng-model="settingsVm.settingsForm.StreetName" required />
<div class="error-message" ng-show="settingsVm.settingsForm.StreetName.$invalid && settingsVm.settingsForm.StreetName.$touched || listingVm.submitted">
<span ng-show="settingsVm.settingsForm.StreetName.$error.required">Street Name is required.</span >
</div>
</div>
</div>
</form>
Am I using the ng-model correctly? And am I using the $error correctly?
Should my model be a distinct object from my form? Maybe my model should point at settingsVm.settingsData instead of settingsVm.settingsForm.
Here is my submit:
vm.submit = function (isValid) {
vm.submitted = true;
if (isValid) {
settingsService.putSettings(vm.settingsForm);
}
};
Not sure if this will help you after 3 months, but I figured it out, please correct me if I am wrong somewhere.
Yes your statement is right, you actually need to separate form validation and input fields.
I assume when you are using field validation angular actually uses input field names not the ng-Model values. So this works for me
var myapp = angular.module("taskApp", [])
.controller("taskCtrl", function($scope, $http) {
$scope.form = {};
$scope.makeTask = function(data) {
console.dir(data);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-App="taskApp" ng-controller="taskCtrl">
<form name="TaskForm" novalidate ">
<div class="form-group ">
<label>Name</label>
<input name="Name " ng-required="true " class="form-control " ng-model="form.Name " />
<span ng-show="TaskForm.Name.$invalid && TaskForm.Name.$dirty ">The name is required</span>
</div>
<button ng-Click="makeTask(form) " type="submit ">Add</button>
</form>
<div id="output ">OUTPUT</div>

Angular validator, pass data along with error code to be displayed in ngMessages

Is that possible to store some additional data along with the error flag itself, using standard Angular mechanism?
i.e. I'm manually setting ngModel.$setValidity, I'd like to pass some data along with the error flag, to be displayed in ngMessages directive.
For example let's assume the min/max length of the field depends upon some external factors, thus is computed & validated server-side. The server respons with customlength error code along with max and min properties, which I'd like to display to the user.
Currently I'm simply setting ngModel.$setValidity("customlength", false); but I'd like to pass {max: response.max, min: response.min} along, to be interpolated in the template like <div ng-message="customlength">the length should be between {{ data.min }} and {{ data.max }}
I'd like to pass {max: response.max, min: response.min} along, to be interpolated in the template like the length should be between {{ data.min }} and {{ data.max }}
Use the root scope to store the value(s) intended to be output within the message string:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-messages.js"></script>
<script>
angular.module('ngMessagesExample',['ngMessages']);
</script>
<body ng-app="ngMessagesExample">
<form name="myForm" id="{{$root.$id}}">
<label>
<p>Enter Min:<input type="text" ng-model="form_min">
<p>Enter Max:<input type="text" ng-model="form_max">
<p>Enter your name:
<input type="text"
name="myName"
ng-model="name"
ng-minlength="form_min"
ng-maxlength="form_max"
required />
</label>
<p>
<input type="radio" required name="foo" ng-model="foo" value="1">Yes
<input type="radio" required name="foo" ng-model="foo" value="2">No
</p>
<p>
Foo: <input type="text" ng-model="myForm.foo.$modelValue">
</p>
<p>
<input type="submit" value="{{myForm.foo.$error.required ? 'No' : 'Yes'}}">
</p>
<pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>
<div ng-messages="myForm.foo.$error" style="color:maroon" role="alert">
<div ng-message="required">Pick one</div>
</div>
<div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
<div ng-message="required">Your value should be between {{form_min}} and {{form_max}} characters long</div>
<div ng-message="minlength" id="{{$id}}">Your value is less than {{form_min}}</div>
<div ng-message="maxlength" id="{{$id}}">Your value is greater than {{form_max}}</div>
</div>
</form>
</body>
References
Easy Form Validation in AngularJS with ngMessages — SitePoint
AngularJS: Developer Guide: Migrating from Previous Versions
Explicitly providing ng-model to DOM elements | TO THE NEW Blog
Using NgModelController with Custom Directives

Angular form name is passed as string when passed as parameter

I'm simply trying to reset a form using the angular functions $setPristine & $setUntouched (several forms are created with ng-repeat).
I assign the form name dynamically by using the syntax {{ someName }} (the name is build on the server side and is passed as json (string)).
The name of the form is correctly assigned in the markup and validations are working as expected. The problem arrises when I pass that name as a parameter in the ng-click="reset(someName)" function.
When debugging the name comes as a string and not as the form object which causes the error. I did a quick test by hard-coding the name and pass that same name and it works fine.
My assumption is, the name coming from json is a string and the type is forwarded to the function as is, instead of the object.
So the question is: is there a way to convert that name so it is interpretated correctly by the controller. Or maybe there is something else I'm missing...
Here is the markup ( notice the name of the form uses {{ resto.contactForm }} ):
<form novalidate name="{{ resto.contactForm }}" ng-submit="submit(restoContact, resto.contactForm.$valid)" class="sky-form">
<div class="form-group">
<label class="checkbox state-success">
<input type="checkbox" ng-model="restoContact.sameAsUser" name="sameAsUser" id="sameAsUser" value="true" ng-click="contactAutoFill()"><i></i>Contact name is same as current user.
<input type="hidden" name="sameAsUser" value="false" />
</label>
</div>
<div class="form-group">
<label class="control-label" for="contactName">Contact Name</label>
<input type="text" ng-model="restoContact.contactName" name="contactName" id="contactName" placeholder="John, Doe" class="form-control" required />
<div ng-show="{{ resto.contactForm }}.contactName.$error.required && !{{ resto.contactForm }}.contactName.$pristine" class="note note-error">Please enter a name or check the box 'Same as current user'.</div>
</div>
<div class="form-group">
<label class="control-label" for="contactPhoneNumber">Contact Phone Number</label>
<input type="text" ng-model="restoContact.contactPhoneNumber" name="contactPhoneNumber" id="contactPhoneNumber" placeholder="+1 555-1234-567" class="form-control" required ng-pattern="phoneNumberPattern" />
<div ng-show="({{ resto.contactForm }}.contactPhoneNumber.$error.required || {{ resto.contactForm }}.contactPhoneNumber.$error.pattern) && !{{ resto.contactForm }}.contactPhoneNumber.$pristine" class="note note-error">Please enter a valid phone number.</div>
</div>
<div class="margin-leftM19">
<button class="btn btn-primary">Save Changes </button>
<button class="btn btn-default" ng-click="reset(resto.contactForm)">Cancel </button>
</div>
</form>
Here is the reset function in the controller (form comes as "contactForm1" which is the correct name but is a string and not the object):
$scope.reset = function (form) {
if (form) {
form.$setPristine();
form.$setUntouched();
}
//$scope.user = angular.copy($scope.master);
};
I have not implemented th submit method but I'm sure I will be running into the same issue.
Any suggestions or advices are welcome.
Thanks in advance...
Here is the fidle.js. the variable data is an exact response from the server.
[http://jsfiddle.net/bouchepat/v0mtbxep/]
SOLUTION:
http://jsfiddle.net/bouchepat/v0mtbxep/3/
I removed $setUntouched as it throws an error.
You can't dynamically name a <form> or <ng-form>.
Although what you want, is make the form usable in the controller. You could do the following:
// in controller
$scope.form = {};
$scope.reset = function() {
$scope.form.contact.$setPristine();
$scope.form.contact.$setUntouched();
};
// in html
<form name="form.contact">
This is happening because resto.contactForm is a string defined on the scope. The angular directive for form is just creating a variable on the scope with the same name. To get the variable by a string, use $eval. This should work:
$scope.reset = function (formName) {
var form = $scope.$eval(formName);
if (form) {
form.$setPristine();
form.$setUntouched();
}
//$scope.user = angular.copy($scope.master);
};

Ng-model does not update view

I have searched thoroughly everywhere and can't seem to find the solution to my problem.
I am trying to make a form to fill in to create new task object onto projects on the website like a scrum backlog or something in Angular and angular-ui.
I use Angular-UI for typeahead functionality for when adding team members to a task, so available members on a project pop-up. I have seen guys with similar problems, but nothing seems to solve it for me. Below is the HTML and the controller. Sorry for the long markup, but I suspect it has to do something with nesting the controllers and mixing the scopes, so I'm including everything relevant.
<div ng-controller="SubmitCreateTaskController">
<div class="modal fade" id="taskModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">New Task</h4>
</div>
<div class="modal-body">
<form role="form" method="post" name="create-task">
<div class="form-group">
<label for="taskname">Task Name</label>
<input type="text" class="form-control" id="taskname" ng-model="taskForm.taskName" placeholder="Task Name">
</div>
<div class="form-group">
<label for="taskdesc">Description</label>
<textarea class="form-control" id="taskdesc" size="3" ng-model="taskForm.taskDescription" placeholder="Enter a short description here..." rows="2"></textarea>
</div>
<div class="form-group">
<label for="assigneddate">Assigned Date</label>
<input type="text" class="form-control" id="assigneddate" ng-model="taskForm.assignedDate">
</div>
<div ng-controller="TypeAheadController">
<div class="form-group">
<label for="contributors">Add Contributors</label>
<input id="contributors" type="text" class="form-control" ng-model="contrib.selected" typeahead="member for member in contrib.stream_members | filter:$viewValue"
typeahead-editable="false" typeahead-on-select="contrib.onSelect($item)">
</div>
<div class="form-group">
<label for="users">Contributors:</label>
<textarea class="form-control" disabled="disabled" id="users" ng-model="contrib.entered" rows="1"></textarea>
</div>
</div>
<div class="form-group">
<label for="taskcomments">Comments</label>
<textarea class="form-control" id="taskcomments" ng-model="taskForm.comment" placeholder="Comments" rows="2"></textarea>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" ng-click="taskForm.submit()">Add Task</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
Controllers:
.controller('SubmitCreateTaskController', ['$scope', '$http', function($scope, $http) {
$scope.taskForm = {};
$scope.taskForm.taskName = '';
$scope.taskForm.taskDescription = '';
$scope.taskForm.assignedDate = new Date();
$scope.taskForm.contributors = [];
$scope.taskForm.comment = '';
$scope.taskForm.submit = function(item, event) {
var formData = {name: $scope.taskForm.taskName,
description: $scope.taskForm.taskDescription,
status: 'open',
assigned: $scope.taskForm.assignedDate,
completed: null,
contributors: $scope.taskForm.contributors,
comments: [{body: $scope.taskForm.comment,
user: 'RACHE User',
date: new Date()
}]
};
var postURL = '../create_task/' + $scope.stream_name;
$http.post(postURL, formData)
.success(function(){
taskForm = {}; // empty the form of previous input values
alert('New Task Created for ' + $scope.stream_name);
})
.error(function(res) {
alert(res.data);
});
};
}])
.controller('TypeAheadController', ['$scope', '$http', function($scope, $http) {
$scope.contrib = {};
$scope.contrib.selected = '';
$scope.contrib.stream_members = undefined;
$scope.contrib.entered = [];
$http.get('/stream_members/' + $scope.stream_name)
.then(function(res) {
$scope.contrib.stream_members = res.data.stream_members;
});
$scope.contrib.onSelect = function($item) {
$scope.contrib.selected = '';
$scope.contrib.entered.push($item);
console.log($scope.contrib.entered);
};
This last bit is the important part in 'TypeAheadController'. I am trying to add the poped-up team members to a textarea just below which would be sent to the DB later. That is why I have bound the actual typeahead input box to 'contrib.select' and the "display/post" box to 'contrib.entered', so the search can be continued after adding one member, the search box is cleared, selected member is added to box below, new search can begin. In the mark up I call the last (onSelect) function in the typeahead-on-select callback. This so that I can clear the input box and another member can be easily added without deleting manually. IN this function the entered member should be appended to the array that is bound to below "display/post" box. This happens, since the console log shows good value, the search/input field gets cleared, so the function gets called as well.
The view does not get updated with the updated array bound to display box however. I have tried EVERYTHING. I have googled around and found it here that dot notation needs to be used as Angular can't update with primitives, but this hasn't helped either.
Everything works fine, the logic is good, values are good when I print them out, pop-up works and clears up as expected, but The damn textarea under it does not get updated.
Any suggestions? I have been stuck on this for almost a day now and I am really frustrated by this. I would be ever so greatfull for any help!
Thanks guys in advance!
Textarea do use the value attribute, your code isn't working because contrib. entered isn't between the tags, but because you can not bind the textarea to an array (it needs to bind to a string).
look at this plunker, if you do this in your html:
<textarea class="form-control" disabled="disabled" id="users" rows="1" ng-model="contrib.enteredString"></textarea>
and add this line at the end of your typeahead controller:
$scope.contrib.enteredString = $scope.contrib.entered.toString();
then the text area will update
Textareas don't use the ng-value as their value is contained within the tag. Remove the ng-model and put the value between the tags.
<textarea class="form-control" disabled="disabled" id="users" rows="1">{{contrib.entered}}</textarea>

Resources