Function to add and show up a new object in an array - arrays

I just got started with playing around with AngularJS and I would like to build an app, that just adds another person´s name and his/her date of birth.
I have got already initial data (2 persons and their date of birth (dob).
By writing down the full name and dob and then pressing the add button, I would like to have another person added as well as his/her dob - and this new person should be also listed and visible in the list.
So far I made it that the function creates a new object. But unfortunately I am not able to combine the input data with the new added object in a proper way.
Can somebody help me? Maybe there is an easier way to do it
So far I created this:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
<script>
var app = angular.module("myBirthApp",[]);
app.controller("myCtrl", function($scope){
$scope.birthdays=[
{fullName:'Jane Doe', dateOfBirth:'08.03.1990'},
{fullName:'John Doe', dateOfBirth:'19.11.1995'}];
// create new array with addItem!
$scope.addItem = function () {
$scope.birthdays.push($scope.addMe);
}
});
</script>
<div ng-app="myBirthApp" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in birthdays"><p>Name: {{x.fullName}}</p> <p>Date of birth: {{x.dateOfBirth}}</p> </br></li>
</ul>
<form>
<fieldset>
<legend>Add a person</legend>
First name and last name: <input type="text" ng-model="fullName"></br>
Date of birth: <input type="date" ng-model="dateOfBirth"></br>
<button ng-click="addItem()">Add</button>
</fieldset>
</form>
</div>
</body>
</html>

You could declare a variable:
$scope.person = {
fullName: '',
dateOfBirth: null
};
and bind it to ngModel inputs:
<input type="text" ng-model="person.fullName"><br />
<input type="date" ng-model="person.dateOfBirth">
and then in addItem method push it to birthdays array. (Of course it needs further additions, validation checks etc but this is the basic idea)
Check here a working demo: DEMO

Related

How to validate AngularJS form input while is using ng-repeat

I have a form which has input fields that is dynamically built using ng-repeat. How I can validate these fields are greater than another input field. Please look at this sample code.
<html ng-app>
<head>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body ng-init="weekDays = ['monday', 'tuesday', 'wednesday','thursday', 'friday', 'saturday','sunday']">
<h1>Fun with Fields and ngModel</h1>
<p>days: {{weekDays}}</p>
<h3>Binding to each element directly:</h3>
<div ng-repeat="weekday in weekDays">
Value: {{weekday}}
{{day='day_'+weekday; ""}}
<input name="{{day}}" ng-model="val">
</div>
<div>
Number to validate : <input name="numToValidate">
</div>
</body>
I am very new to angularJS and still learning. However I couldn't able to think through this simple validation. Please help.
Html:
<form name="form">
<div ng-repeat="weekday in weekDays">
Value: {{weekday}}
{{day='day_'+weekday; ""}}
<input name="{{day}}" ng-model="val" required>
</div>
<div>
Number to validate : <input name="numToValidate" required>
</div>
</form>
Script:
if($scope.form.$valid){
// You can write your code here what you want to do after validate.
}
You can use html form element with min attribute to check validity
<input name="{{day}}" ng-model="weekday.val" min="{{numToValidate}}">
you will need seperate model for each of your inputs in your ng-repeat therefore I changed your ng-model with the following
ng-model="weekday.val"
if you do not want to use form you can check the validity of your value with ng-blur directive (triggered when input loses focus).
html
<input name="{{day}}" ng-model="weekday.val" ng-blur="checkValid(weekday.val)">
js
$scope.checkValid = function(value){
if(value > $scope.numToValidate){
alert("please enter a valid number");
}
}

RESTAngular with factory method is not working

Following the tips in
Best practice of RestAngular, I am trying to follow the suggestions (Restangular Service - Factory and exampleService) and it's not working.
The following source code includes two sections one. Without Angular Factory, that works. And with Factory that is not working:
<html ng-app="angularexample">
<head>
<script src="https://code.angularjs.org/1.3.14/angular.min.js"></script>
<script src="https://code.angularjs.org/1.3.14/angular-route.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/restangular/1.5.1/restangular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-Controller='MainCtrl'>
<div ng-repeat="user in users">
Name : {{user.name}}<br>
Age : {{user.age}}<br>
ID : {{user.id}}<br>
Change name:<input type="text" ng-model="user.name"/><button type="submit" ng-click="user.put()">Update</button><br/>
Remove ID:<input type="text" ng-model="user.id"/><button type="submit" ng-click="user.remove()">Delete</button><br/>
</div>
<div>
add new: <br/>
Name : <input type="text" ng-model="newUser.name"/><br/>
Age : <input type="text" ng-model="newUser.age"/><br/>
<button type="submit" ng-click="add()">add</button>
</div>
</div>
<div ng-Controller='ExampleCtrl'>
My Title {{title}} <br/>
<div ng-repeat="user in examples">
Name : {{user.name}}<br>
Age : {{user.age}}<br>
ID : {{user.id}}<br>
Change name:<input type="text" ng-model="user.name"/><button type="submit" ng-click="user.put()">Update</button><br/>
Remove ID:<input type="text" ng-model="user.id"/><button type="submit" ng-click="user.remove()">Delete</button><br/>
</div>
<div>
add new: <br/>
Name : <input type="text" ng-model="newUser.name"/><br/>
Age : <input type="text" ng-model="newUser.age"/><br/>
<button type="submit" ng-click="add()">add</button>
</div>
</div>
</body>
</html>
http://plnkr.co/edit/y22aBpcUwV1btrKB5jVM?p=preview
Here is the error screen:
http://i57.tinypic.com/334rfqu.jpg
The working reference is pictured as my REST service is not hosted . Yet my REST service is just having two fields namely - name and age.
/**
* User.js
*
* #description :: This is the sample Model for Sails JS to create REST API.
* #docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
name : {
type : 'string'
},
age : {
type : 'integer'
}
}
};
What could be an issue in my code? I would like to follow the best practices to build a big application.
The code fails because your service methods do not return anything. Update them as follows:
// get examples from server by using Restangular
function getExamples(){
return Restangular.all('user').getList();
}
You are calling the then method without returning the associated promise from your factory methods, you should return the promise, like
// get examples from server by using Restangular
function getExamples(){
return Restangular.all('user').getList();
}
// get example with given id from server by using Restangular
function getExample(exampleId){
return Restangular.one('user', exampleId).get();
}
Now the methods will make the request and return the assoiciated promise on which you can call the then method.

Angularjs default value of radio button is not working

I'm new here and this is my first post. Please let me know if I do anything wrong, thanks.
Recently I'm working on an account management page using angularjs. I'm having a problem when setting default checked to gender radio buttons. I use bit in database to record gender and yes I've tried ng-value but it doesn't work. Here is my code:
var module = angular.module("MainApp", []);
module.controller('GlobalCtrl',
function ($scope, $http) {
$scope.testerSet = [{ name: 'Ysoda', Gender: true, age: 9 }, { name: 'Lydia', Gender: false, age: 9 }];
$scope.setCurrentTester = function () {
if ($scope.testerCollection[0] != null) {
$scope.currentTester = $scope.testerCollection[0];
// $scope.$apply();
}
};
});
<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.22/angular.min.js"></script>
<div ng-app='MainApp'>
<div ng-controller='GlobalCtrl'>
{{testerSet[0].name}}
<select multiple ng-model="testerCollection" style="width: 100%; height: 400px" ng-options="tester.name for tester in testerSet" ng-change="setCurrentTester();">
</select>
<div>
<label>Gender:</label>
{{currentTester.name}}
{{currentTester.Gender}}
<label><input type="radio" runat="server" name="genderSet" ng-model="currentTester.Gender" ng-value=true id="radioMale" /> Male</label>
<label><input type="radio" runat="server" name="genderSet" ng-model="currentTester.Gender" ng-value=false id="radioFemale" /> Female</label>
</div>
</div>
</div>
I use multiple select to show a select as a listbox, I'm thinking that might be the reason why it doesn't work. I've spent hours working on this little button and I just don't know why names and account and all other data work well but the gender radio boxes do not.
I use {{currentUser.Gender}} to check value and the value shows correct. However, the default check still doesn't work.
Thank you for your time.
<input type="radio" runat="server" name="genderSet" ng-model="currentUser.Gender" ng-value=true id="radioMale" /> Male
ng-value="true" give the value without quotes ng-value=true

Work with multiple Forms and its values

Assume an certain amount of forms created by ng-repeat, which allows the user to sum something up like a+b and display the result instantly.
How would the Controller look like?
<div data-ng-repeat="form in forms">
<form name={{form.name}}>
<input type="text" name="a" ng-modal="?">
<input type="text" name="b" ng-modal="?">
</form>
<p>{{?.result}}</p>
</div>
The question marks within the html should be something unique I guess. And the controller may access something like an array of forms from scope ... but maybe someone has a suggestion
If I understand your question correctly and assuming you have defined the forms in an array for example, below code should work for you:
<!DOCTYPE html>
<html data-ng-app="formApp">
<head>
<script type="text/javascript" src="https://code.angularjs.org/1.2.26/angular.js"></script>
<script type="text/javascript">
var formApp = angular.module("formApp",[]);
formApp.controller("formController", function($scope)
{
$scope.forms = [{name: "Foo"}, {name: "Bar"}];
});
</script>
</head>
<body data-ng-controller="formController">
<div data-ng-repeat="form in forms">
<form name={{form.name}}>
<input type="text" name="a" data-ng-model="form.someField">
<input type="text" name="b" data-ng-model="form.someOtherField">
</form>
<p>{{form.someField + form.someOtherField}}</p>
</div>
</div>
</html>
So basically you were right when mentioning "array of forms from scope".
The important thing to know is that angular creates a new scope for every item in the collection when using ng-repeat. This means, you do not need to use unique member names. "form.someField" for example always references the member of the current scope.
The calculation you would like to perform could be done inline as in my example or you could move it to an own method on a "class" from which all items in the form collection will inherit.
By the way: it's "data-ng-model" and not "data-ng-modal" ;)

Binding repeatable form subset to model

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>

Resources