Binding user input data to AngularJS object - javascript

Im working on a project where I input a user's Id, first name and last name. Once input, I create a user object which is stored inside the logins array.
What I'm trying to do is display each new user as the next item in an unordered list each time the login button is clicked. Right now, I'm trying to get the user input from the text boxes, this works for the first item, until I try to clear the text boxes. How can I correctly bind my input to the user object while still being able to display each new user? I.e, add more than one user and have them both show up. They seem to be added to the array fine, but I can't figure out where the display is going wrong.
I'm thinking that because of the way I'm trying to get the data input to the text boxes, my variables are set as I enter them, but I'm not sure what else I can try. Quite new to angular. Any help is appreciated.
Code:
<!DOCTYPE html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js"></script>
<script type='text/javascript'>
function LoginController($scope) {
$scope.user = {
id: "",
firstName: "",
lastName: ""
};
$scope.logins = [];
$scope.login = function () {
$scope.logins.push($scope.user);
console.log($scope.logins);
};
}
</script>
</head>
<body>
<div ng-controller="LoginController">
<div>Hello {{ user.firstName }}</div>
<input id="id" ng-model="user.id"></input>
<input id="first" ng-model="user.firstName"></input>
<input id="last" ng-model="user.lastName"></input>
<input type="submit" ng-click="login()" value="Login"></input>
<ul>
<li ng-repeat="login in logins" >{{user.id + ', ' + user.firstName + ', ' + user.lastName}}</li>
</ul>
</div>
</body>
</html>

you cannot add same object (duplicate) that you have used for repeater,
you want some like this,
check below or check on https://jsbin.com/pulinetari/1/edit?html,console,output
check
$scope.logins.push({id:$scope.user.id, firstName: $scope.user.firstName, lastName: $scope.user.lastName});
you need to create new object to add on array, which uses by repeater.
<!DOCTYPE html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js"></script>
<script type='text/javascript'>
function LoginController($scope) {
$scope.user = {
id: "",
firstName: "",
lastName: ""
};
$scope.logins = [];
$scope.login = function () {
$scope.logins.push({id:$scope.user.id, firstName: $scope.user.firstName, lastName: $scope.user.lastName});
console.log($scope.logins);
};
$scope.selectUser= function(user){
$scope.user = user;
}
}
</script>
</head>
<body>
<div ng-app ng-controller="LoginController">
<div>Hello {{ user.firstName }}</div>
<input id="id" ng-model="user.id"></input>
<input id="first" ng-model="user.firstName"></input>
<input id="last" ng-model="user.lastName"></input>
<input type="submit" ng-click="login()" value="Login"></input>
<ul>
<li ng-repeat="login in logins" ng-click="selectUser(login)">{{login.id + ', ' + login.firstName + ', ' + login.lastName}}</li>
</ul>
</div>
</body>
</html>

Related

Submitting data in AngularJS form using ng-model inside ng-repeat

I'm having the same problem as in this question, but the solutions there do not work for me.
I'm learning AngularJS and I am struggling to submit form data using ng-model inside of ng-repeat. I have a list of members of a group and the date they last attended:
[{"name": "Bob", "attended": "01/01/16"},
{"name":"Steve", "attended": "02/01/16"}]
I'm listing out all members using ng-repeat, and would like to be able to update the "attended" field from a form in each line. However, I cannot get "attended" to bind properly. Here's the code:
<div ng-repeat="member in members">
{{member.name}}
<input type="text" ng-model="attended"></input>
Save
</div>
$scope.setAttended = function(attended){
alert( 'Date: ' + attended);
};
The alert shows "Date: undefined". I've also tried using objects instead of primitives:
<div ng-repeat="member in members">
{{member.name}}
<input type="text" ng-model="member.attended"></input>
Save
</div>
$scope.setAttended = function(member){
alert( 'Date: ' + member.attended);
};
I get that ng-repeat will create a new scope for each object, and those scopes inherit setAttended from the parent scope. I get that the parent scope doesn't know what is happening in the child scopes, and so the parameter must let it know.
Why doesn't my parameter contain my input value?
Is the input not being bound to the model correctly before I run setAttended?
Actually it is working for me. See the snippet below.
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular-route.min.js"></script>
<style>
</style>
</head>
<body ng-controller="myController">
<div ng-repeat="member in members">
{{member.name}}
<input type="text" ng-model="member.attended"/>
Save
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myController", function($scope) {
$scope.members = [{
"name": "Bob",
"attended": "01/01/16"
}, {
"name": "Steve",
"attended": "02/01/16"
}];
$scope.setAttended = function(member) {
alert('Date: ' + member.attended);
}
});
</script>
</body>
</html>
Please try below code and feedback me:
<div ng-repeat="member in members">
{{member.name}}
<input type="text" ng-model="members[$index].attended"></input>
Save
</div>
$scope.setAttended = function(attended){
alert( 'Date: ' + attended);
};
Use this , It refers to the correct scope object from ng-repeat function
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.members = [{"name": "Bob", "attended": "01/01/16"},
{"name":"Steve", "attended": "02/01/16"}];
$scope.setAttended = function(member){
alert( 'Date: ' + this.attended);
};
});
<script data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js" data-require="angular.js#1.4.x"></script>
<body ng-app="plunker" ng-controller="MainCtrl">
<div ng-repeat="member in members">
{{member.name}}
<input type="text" ng-model="attended">
Save
</div>
</body>

ng-model value of input text box is undefined inside angularjs controller when set dynamically through javascript

In my HTML Page i am setting an input text box value not by typing but through JavaScript and then when I am fetching that value using AngularJS inside the controller using scope, then it's showing undefined....
Below is my code:-->
<!DOCTYPE html>
<html lang="en">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form id="someForm" name="someForm">
First Name: <input type="text" id="fname" ng-model="user.firstname" ng-model-options="{updateOn: 'change'}" />
Last Name: <input type="text" id="lname" ng-model="user.lastname" ng-model-options="{updateOn: 'change'}" />
<input id="getUser" type="submit" ng-click="getUserName(user)" value="Get User" />
<button ng-click="resetForm(user)">RESET</button>
</form>
</div>
<script>
$('#getUser').on('click', function(){
//$("getUser").on('click', function(){
//alert("First Name "+$("#fname").val());
$("#lname").val($("#fname").val());
alert("Last Name set to "+$("#lname").val());
// });
});
</script>
<script>
//angular.element(document).ready(function () {});
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.getUserName = function(user)
{
alert("Last Name in Angular Controller: "+$scope.user.lastname)
}
$scope.resetForm = function(user) {
//Even when you use form = {} it does not work
angular.copy({},user);
}
});
</script>
</body>
</html>
After clicking Get User Button, first the lastname field value is set through JQuery then AngularJS controller is called in which the ng-model value is undefined. I am unable to understand this. What is the solution or workaround for this type of scenario where the input text field value is set dynamically through JavaScript or JQuery and fetched and used using AngularJS Model and Controller.
Looks like you have a typo at ng-model="user.lasttname"
<!DOCTYPE html>
<html lang="en">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form id="someForm" name="someForm">
First Name: <input type="text" id="fname" ng-model="user.firstname" ng-model-options="{updateOn: 'change'}" />
Last Name: <input type="text" id="lname" ng-model="user.lastname" ng-model-options="{updateOn: 'change blur'}" />
<input id="getUser" type="button" ng-click="getUserName(user)" value="Get User" />
<input id="getUser2" type="button" ng-click="getUserName(user)" value="Get User" />
<button ng-click="resetForm(user)">RESET</button>
</form>
</div>
<script>
$('#getUser').on('click', function(){
var element = angular.element($('#someForm'));
element.scope().user.lastname = $("#fname").val();
});
</script>
<script>
//angular.element(document).ready(function () {});
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.user = {};
$scope.getUserName = function()
{
console.log("User: "+ JSON.stringify($scope.user));
alert("Last Name in Angular Controller: "+$scope.user.lastname)
}
$scope.resetForm = function(user) {
//Even when you use form = {} it does not work
// angular.copy({},user);
}
});
</script>
</body>
</html>
Add this in angularjs code:-
<script>
//angular.element(document).ready(function () {});
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.user = {}; // Initiate this
$scope.getUserName = function(user)
{
alert("Last Name in Angular Controller: "+$scope.user.lastname)
}
});
Of course!!! If you want the binding (HTML <--> JavaScript) you must respect the rules of Angular. What you need to do is to update the ng-model being defined for the input box. So, add to your input box: ng-model="blabla" and within your JavaScript: $scope.blabla = <value>.
Correction: You do have the ng-model in the input, but still miss the assignment within your javascript code.

Angular JS - Text box not getting updated after clearing

I am a beginner in Angular JS. While creating a sample application I have encountered the below problem of a text box not getting set once the value in its cleared using JavaScript.Below is my code:-
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function () {
this.showName = function () {
this.user = { name: "John" };
}
this.clear = function () {
document.getElementById("name").value = "";
}
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="myCtrl as ctrl" class="container">
<input type="button" ng-click="ctrl.showName()" value="Show Name"/>
<input type="text" id="name" ng-model="ctrl.user.name" />
<input type="button" value="Clear" ng-click="ctrl.clear()" />
</div>
</body>
Her the first time I click on the Show name button I am getting the name in the text box.But if I clear the text box by clicking the Clear button and then click on the show button again the name is not getting filled in the text box.
Can anyone please tell me why this is happening and anyways to fix this?
Here is my code in plunkr - http://plnkr.co/edit/MXlH2o?p=preview
In your clear function do below code to clear value.
this.user = { name: "" };
Clear the name like this,
this.clear = function () {
this.user.name = "";
}
you don't need a clear() method in the controller, just take advantage of the double binding in angular, set the username to an empty string when you click on the button and the view will be updated consequently.
<input type="button" value="Clear" ng-click="ctrl.user.name = ''" />
change clear function to this code
this.clear = function () {
this.user.name="";
}

One form and validation for many objects with different data

Is it possible to check that form is valid in js file, but for many objects? I want to have only one form in html and don't use any of ng-repeats or other loops in html, then check form is valid for all objects.
Exmaple
<!DOCTYPE html>
<html ng-app="AngularApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"> </script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="mainController">
Click on table row if u want to change data in form
<table>
<thead>
<tr>
<td>
Index
</td>
<td>
Name
</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="element in testCollection"
ng-click="changeActiveElement(element)">
<td>{{ $index }}</td>
<td>{{ element.name }}</td>
</tr>
</tbody>
</table>
<br />
<br />
<br />
<form name="exampleForm">
<div class="row">
Name [required]: <input type="text" ng-model="activeObject.name" required>
</div>
<div class="row">
Phone [required]: <input type="text" ng-model="activeObject.phone" required>
</div>
<div class="row">
Active: <input type="checkbox" ng-model="activeObject.active">
</div>
</form>
<br />
<button ng-disabled="">
This button should be enable if all objects from table will pass form validation
</button>
but how to do this? Button should be know that every form is good or not, even if won't change object by clicking on table row.
</body>
</html>
Js:
var app = angular.module("AngularApp", []);
app.controller('mainController', function($scope) {
$scope.testCollection = [
{
name: 'Mike',
phone: 12345678,
active: true
},
{
name: 'Martin',
phone: '',
active: false
},
{
name: 'Anna',
phone: '',
active: ''
}
];
$scope.activeObject = $scope.testCollection[0];
$scope.changeActiveElement = function(element) {
$scope.activeObject = element;
};
});
Yes its possible, so lets say that 'many objects' are like this :
$scope.fianlObject = { manyObj1 : {}, manyObj2 :{}}
then do something like this with HTML :
<form id="frm1" name="frm1" ng-submit="submit()">
<div class="form-group required" ng-class="isInvalid('manyObj1', form1)">
....
</div>
<div class="form-group required" ng-class="isInvalid('manyObj2', form1)">
....
</div>
.
.
</form>
and something like this with script :
$scope.isInvalid = function (manyObj, form) {
if (form&& form.$submitted) {
return ( form[manyObj] && form[manyObj].$invalid) ? 'has-error'
: '';
}
return '';
}
Angular have FormController, that have property $invalid
$invalid
boolean
True if at least one containing control or form is invalid.
and you can use it like
<button ng-disabled="formName.$invalid" ... >
Yes, you can do that.
Just specify you validator function as a pure function which just accepts a plain object with the data and returns an array of errors (empty if everything is ok). This function should know about context it's used in.
Simple example:
function validateForm(data) {
var errors = [];
if (data.name === 'Joe') errors.push("You can't be Joe!");
return errors;
}
Then, every time you want to validate your form, convert your form data to JS object and use the function. Also, you can use such function in any other context, no matter who is initiator of the validation.

JavaScript MadLib game - cannot call function on submit

I am trying to complete a simple exercise to test my JavaScript skills at processing input elements from a form. The object of the game is to retrieve current values from the form input elements, make a story from them, and output that story in the 'story' div. However, when I click the 'Lib It!' button, the function is not getting called, and the text is not being replaced. Any ideas as to why this is not happening?
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>Mad Libs</h1>
<ul>
<li>Noun: <input type="text" id="noun">
<li>Adjective: <input type="text" id="adjective">
<li>Someone's Name: <input type="text" id="person">
</ul>
<button id="lib-button" onclick="makeMadLib">Lib it!</button>
<div id="story">Placeholder Text</div>
<script type="text/javascript" src="exercises.js"></script>
</body>
</html>
JavaScript:
function makeMadLib(){
var noun = document.getElementById("noun").value;
var adjective = document.getElementById("adjective").value;
var person = document.getElementById("person").value;
var story = document.getElementById(story);
story.firstChild.nodeValue = person + "likes taking photographs of" + adjective + noun;
}
Thanks,
Robert
London, Uk
First we forgot to use parentheses when calling the madLib function. Change onclick="makeMadLib" to onclick="makeMadLib()". Then in our madlib function we need to add quotes around the story in document.getElementById() : var story = document.getElementById("story");. Finally to output our text all we have to do is use innerHTML.
HTML
...
<button id="lib-button" onclick="makeMadLib()">Lib it!</button>
...
JS
...
var story = document.getElementById("story");
....
story.innerHTML = person + " likes taking photographs of " + adjective + " " + noun;

Categories

Resources