AngularJs - push Object in array - angularjs

I can't understand how to push object into an array I tried few different ways and still can't figured it out.
var app = angular.module('myApp',[])
app.controller('dropdown', function($scope, $http){
$scope.userInfo = [];
$scope.pushInArray = function() {
$scope.userInfo.push($scope.users)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="dropdown">
<input type="text" name="name" ng-model="users.name" placeholder="Name">
<input type="text" name="email" ng-model="users.email" placeholder="Email">
<input type="text" name="phoneNo" ng-model="users.phoneNo" placeholder="phone Number">
<button ng-click="pushInArray()">Add</button>
<pre>{{userInfo}}</pre>
</div>
at click of add button I push the users information in userInfo properities. I works on first time but If I modified the the value already stored value also modified(after push value is modifying).

try angular.copy, this will copy the exist object with a new instance.
var app = angular.module('myApp',[])
app.controller('dropdown', function($scope, $http){
$scope.userInfo = [];
$scope.pushInArray = function() {
var user = angular.copy($scope.users);
$scope.userInfo.push(user);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="dropdown">
<input type="text" name="name" ng-model="users.name" placeholder="Name">
<input type="text" name="email" ng-model="users.email" placeholder="Email">
<input type="text" name="phoneNo" ng-model="users.phoneNo" placeholder="phone Number">
<button ng-click="pushInArray()">Add</button>
<pre>{{userInfo}}</pre>
</div>

You need to empty yours users before setting it to new values:
$scope.userInfo = [];
$scope.pushInArray = function(data) {
$scope.userInfo.push(data)
$scope.users = null;
}
HTML:
<input type="text" name="name" ng-model="users.name" placeholder="Name">
<input type="text" name="email" ng-model="users.email" placeholder="Email">
<input type="text" name="phoneNo" ng-model="users.phoneNo" placeholder="phone Number">
<button ng-click="pushInArray(users)">Add</button>
<pre>{{userInfo}}</pre>
Here is the working Plnkr

You need to pass the object to the scope function to persist it.
var app = angular.module('myApp',[])
app.controller('dropdown', function($scope, $http){
$scope.userInfo = [];
$scope.pushInArray = function(data) {
var entry = (JSON.parse(JSON.stringify(data)));
$scope.userInfo.push(entry);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="dropdown">
<input type="text" name="name" ng-model="users.name" placeholder="Name">
<input type="text" name="email" ng-model="users.email" placeholder="Email">
<input type="text" name="phoneNo" ng-model="users.phoneNo" placeholder="phone Number">
<button ng-click="pushInArray(users)">Add</button>
<pre>{{userInfo}}</pre>
</div>

Related

AngularJs push form data into json

This is my app.js
volkswagenApp
.controller('VolkswagenCtrl',
['$http' , function($http){
var vw = this;
vw.gegevens = [];
$http.get('autos.json').success(function(data){
vw.gegevens = data;
});
}]);
volkswagenApp
.controller('FormController',function(){
this.gegevens={};
/*this.addGegevens = function(gegeven) {
gegeven.gegevens.push(this.gegeven);
this.gegevens={};
}*/
this.addGegevens = function(gegeven){
this.gegevens.datum = Date.now();
vw.gegevens.push(this.gegeven);
this.gegeven = {};
}
});
and this is my index.html:
<span ng-show="show">
<form name="inputForm" class="form-group" ng-controller="FormController as autoctrl"
ng-submit="inputForm.$valid && autoctrl.addGegevens(gegeven)" novalidate>
<br>
<p> Type: <input type="text" name="autoctrl.type" ng-model="type" style="margin-left:52px; padding-left:5px; width:165px;" minlength="2" maxlength="10" required /></p>
<p>Bouwjaar: <input type="number" name="bouwjaar" ng-model="autoctrl.bouwjaar" style="margin-left:22px; padding-left:5px; width:165px;" minlength="4" maxlength="4" required /></p>
<p>Km: <input type="number" name="km" ng-model="autoctrl.km" style="margin-left:60px; padding-left:5px; width:165px;" minlength="2" maxlength="6" required /></p>
<p>Brandstof: <input id="select" name="brandstof" ng-model="autoctrl.brandstof" style="margin-left:20px; padding-left:5px;" minlength="3" maxlength="7" required/></p>
<p>Kenteken: <input type="text" name="kenteken" ng-model="autoctrl.kenteken" style="margin-left:22px; padding-left:5px; width:165px;" minlength="6" maxlength="9" required /></p>
<p>Datum: <input type="text" name="datum" ng-model="autoctrl.datum" style="margin-left:40px; padding-left:5px; width:165px;" minlength="3" maxlength="11" required /></p>
<p>checked: <input type="checkbox" name="checked" ng-model="autoctrl.checked" style="margin-left:28px;" required /></p>
<br>
<button class="btn btn-primary" type="submit" value="submit">Toevoegen</button>
<div>{{inputForm.$valid}}</div>
and this is the error in the console:
Error: Can't find variable: vw
I know that the variable W isn't defined in FormController, my question is how can i adjust the form controller so that it works.
I tried everything, searched the docs. watched several tutorials and i cant find out where im going wrong. This is for a school project. Please help!
In the FormController add vm = this at beginning.
autoctrl.addGegevens(inputForm) and
in the addGegevens function
this.addGegevens = function(inputForm){
this.gegevens.datum = Date.now();
for (var formField in inputForm){
if(inputForm.hasOwnProperty(formField)){
vw.gegevens.push({formField :inputForm[formField] });
}
}
}
You want to share VW variable to another controller. In order to do this you can use $rootScope. Please check below code which will work for you. Below is the updated span block
<span ng-show="show">
<form name="inputForm" class="form-group" ng-controller="FormController as autoctrl"
ng-submit="inputForm.$valid && autoctrl.addGegevens(gegeven)" novalidate>
<br>
<p> Type: <input type="text" name="autoctrl.type" ng-model="autoctrl.gegevens.type" style="margin-left:52px; padding-left:5px; width:165px;" minlength="2" maxlength="10" required /></p>
<p>Bouwjaar: <input type="number" name="bouwjaar" ng-model="autoctrl.gegevens.bouwjaar" style="margin-left:22px; padding-left:5px; width:165px;" minlength="4" maxlength="4" required /></p>
<p>Km: <input type="number" name="km" ng-model="autoctrl.gegevens.km" style="margin-left:60px; padding-left:5px; width:165px;" minlength="2" maxlength="6" required /></p>
<p>Brandstof: <input id="select" name="brandstof" ng-model="autoctrl.gegevens.brandstof" style="margin-left:20px; padding-left:5px;" minlength="3" maxlength="7" required/></p>
<p>Kenteken: <input type="text" name="kenteken" ng-model="autoctrl.gegevens.kenteken" style="margin-left:22px; padding-left:5px; width:165px;" minlength="6" maxlength="9" required /></p>
<p>Datum: <input type="text" name="datum" ng-model="autoctrl.gegevens.datum" style="margin-left:40px; padding-left:5px; width:165px;" minlength="3" maxlength="11" required /></p>
<p>checked: <input type="checkbox" name="checked" ng-model="autoctrl.gegevens.checked" style="margin-left:28px;" required /></p>
<br>
<button class="btn btn-primary" type="submit" value="submit">Toevoegen</button>
<div>{{inputForm.$valid}}</div>
{{ PostDataResponse}}
{{autoctrl.gegevens.type}}
{{autoctrl.gegevens.bouwjaar}}
</form>
</span>
And you can find the latest app code below
var volkswagenApp = angular.module('volkswagenapp', []);
volkswagenApp.controller('VolkswagenCtrl', ['$http', '$rootScope', function ($http, $rootScope) {
var vw = this;
vw.gegevens = [];
$http.get('autos.json').success(function (data) {
vw.gegevens = data;
});
$rootScope.VolksWagenAppScope = vw;
}]);
volkswagenApp.controller('FormController', ['$rootScope', function ($rootScope) {
this.gegevens = {};
//var vw = this;
// vw.gegevens = [];
/* this.addGegevens = function(gegeven) {
gegeven.gegevens.push(this.gegeven);
this.gegevens={};
}*/
this.addGegevens = function (gegeven) {
debugger;
this.gegevens.datum = Date.now();
$rootScope.VolksWagenAppScope.gegevens.push(this.gegevens);
this.gegevens = {};
}
}]);
It's normal.
In your second controller (FormController), there is no vw var declared.
You can add it as you did in the first controller :
var vw = this
Ideal way will be using a `factory' to store the results, and use that factory share data between two controller.
volkswagenApp
.factory('gegavensFactory', function() {
var _gegevens = [];
return {
init: function(gagaves) {
_gegavens = gegavens;
},
add: function(gegaven) {
_gegavens.push(gegaven);
}
}
)}
volkswagenApp
.controller('VolkswagenCtrl',
['$http', 'gegavensFactory' , function($http, gegavensFactory){
$http.get('autos.json').success(function(data){
gegavensFactory.init(data);
});
}]);
volkswagenApp
.controller('FormController',['gegavensFactory', function(gegavensFactory){
this.gegevens={};
this.addGegevens = function(gegeven){
this.gegevens.datum = Date.now();
gegavensFactory.add(this.gegeven);
this.gegeven = {};
}
}]);

Reset form on submit

I am submitting a form and then making all the field empty but it's not working. Form is getting submitted successfully but the fields are not getting reset. I am using angular-material for styling. Updated controller.
Html
<form name="myform">
<md-input-container>
<label for="name">Contact Name</label>
<input type="text" md-maxlength="20" required="" md-no-asterisk name="name" ng-model="info.name" md-autofoucs>
<div ng-messages="myform.name.$error" role="alert">
<div ng-message="required">This is required.</div>
<div ng-message="md-maxlength">The name has to be less than 20 characters long.</div>
</div>
</md-input-container>
<md-input-container>
<label for="phone">Phone Number</label>
<input type="text" name="phone" required md-no-asterisk ng-model="info.phone">
<div ng-messages="myform.phone.$error">
<div ng-message="required">This is required.</div>
</div>
</md-input-container>
<md-input-container>
<label for="email">Email</label>
<input type="text" name="email" ng-model="info.email">
</md-input-container>
<md-input-container>
<md-button class="md-primary" ng-click="saveit(info)">Save</md-button>
<md-button class="md-primary">Cancel</md-button>
</md-input-container>
</form>
**Function in Controller**
angular.module('contact', ['ui.router', 'ngMaterial', 'templates','ngMessages'])
.config(['$mdThemingProvider', '$stateProvider', function ($mdThemingProvider, $stateProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('blue')
.accentPalette('orange');
$stateProvider
.state('home', {
url: '',
templateUrl: 'templates/home.html',
controller: 'MainCtrl as vm'
});
}]).controller('MainCtrl', function ($scope, $mdSidenav,$mdDialog,$mdToast, contacts) {
var vm = this;
$scope.searchText ="";
$scope.toggleSidenav = function(){
$mdSidenav('left').open();
};
contacts.getall().then(function(response){
console.log(response.data);
$scope.people = response.data;
});
$scope.saveit = function(detail, myform){
if (!detail.name || !detail.phone) { return ;}
contacts.add({
name: detail.name,
phone: detail.phone,
email: detail.email
});
$mdToast.show(
$mdToast.simple()
.content("ContactAdded!")
.position('top, right')
.hideDelay(2000)
);
$scope.people.push(detail);
$scope.info = {};
$scope.myform.$setPristine();
$scope.myform.$setUntouched();
};
$scope.showConfirm = function(ev, person) {
var confirm = $mdDialog.confirm()
.title('Are you sure?')
.ariaLabel('Lucky day')
.targetEvent(ev)
.ok('Please delete it!')
.cancel('I want to keep it.');
$mdDialog.show(confirm).then(function() {
contacts.deletethis(person.id).then(function(){
$mdToast.show(
$mdToast.simple()
.content("Deleted!")
.position('top, right')
.hideDelay(2000)
);
});
var index = $scope.people.indexOf(person);
$scope.people.splice(index,1);
}, function() {
$scope.status = 'You decided to keep your debt.';
});
}; });
<form name="myform">
<input type="text" ng-model="info.name">
<input type="text" ng-model="info.phone">
<input type="text" ng-model="info.email">
</form>
app.controller('MainCtrl', function($scope) {
$scope.info = {}; // name, phone, email
$scope.saveit = function() {
$scope.info.name = ''; // reset name
$scope.info.phone= ''; // reset phone
$scope.info.email= ''; // reset email
// reset form and disable error messages
$scope.myform.$setPristine();
$scope.myform.$setUntouched();
};
});
You are not using $scope and this for controller correctly. You can use $scope or controller as syntax to bind your scope with view.
I suggest you to read more about it here.
Update your saveit() function inside controller as below:
app.controller('MainCtrl', function($scope, $mdSidenav, $mdDialog, $mdToast) {
var vm = this;
vm.info = {};
//your rest the code
vm.saveit = function() {
//do your operations here
vm.info = {};
};
});
Update your html page as below:
<div ng-controller="MainCtrl as vm">
<form name="myform">
<md-input-container>
<label for="name">Contact Name</label>
<input type="text" ng-maxlength="20" required md-no-asterisk name="name" ng-model="vm.info.name" md-autofoucs>
</md-input-container>
<md-input-container>
<label for="phone">Phone Number</label>
<input type="text" name="phone" required md-no-asterisk ng-model="vm.info.phone">
</md-input-container>
<md-input-container>
<label for="email">Email</label>
<input type="text" name="email" ng-model="vm.info.email">
</md-input-container>
<md-input-container>
<md-button class="md-primary" ng-click="vm.saveit()">Save</md-button>
<md-button class="md-primary">Cancel</md-button>
</md-input-container>
</form>
</div>
Give $setPristine to reset the form after saving.
$scope.myform.$setPristine();
Another approach
app.controller('MainCtrl', function($scope, $mdSidenav, $mdDialog, $mdToast) {
var vm = this;
vm.info = {};
vm.saveit = function($event)
{
var form = angular.element($event.target).parent("form")[0];
if (form !== undefined) form.reset();
};
});
<div ng-controller="MainCtrl as vm">
<form name="myform">
<md-input-container>
<label for="name">Contact Name</label>
<input type="text" ng-maxlength="20" required md-no-asterisk name="name" ng-model="vm.info.name" md-autofoucs>
</md-input-container>
<md-input-container>
<label for="phone">Phone Number</label>
<input type="text" name="phone" required md-no-asterisk ng-model="vm.info.phone">
</md-input-container>
<md-input-container>
<label for="email">Email</label>
<input type="text" name="email" ng-model="vm.info.email">
</md-input-container>
<md-input-container>
<md-button class="md-primary" ng-click="vm.saveit($event)">Save</md-button>
<md-button class="md-primary">Cancel</md-button>
</md-input-container>
</form>
</div>
The answer below is missing one line of code to work properly
You can check the answer from another question right here:
https://stackoverflow.com/a/40267630/4767208

How to track two dimentional array data using Angularjs

I am new to Angularjs. I learned some basic concepts and I started developing a form. According to my requirements, I have to give 4 textboxes and if user wants wants more he adds another 4 textboxes. Meanwhile, I am unable to track the entered details.
// create angular app
var validationApp = angular.module('validationApp','');
// create angular controller
validationApp.controller('mainController', function($scope) {
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.showChoiceLabel = function (choice) {
return choice.id === $scope.choices[0].id;
};
$scope.removeChoice = function() {
if($scope.choices.length>1){
var newItemNo = $scope.choices.length-1;
$scope.choices.pop();
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="validationApp" ng-controller="mainController">
<div class="form-group" data-ng-repeat="choice in choices">
<label for="choice" ng-show="showChoiceLabel(choice)">Family Details</label>
<input type="text" ng-model="choice.name" name="id.family_name" class="form-control" placeholder="Enter Family Memeber Name" size="20">
<input type="text" ng-model="choice.relation" name="id.family_relation" class="form-control" placeholder="Enter Relation" size="15">
<input type="text" ng-model="choice.age" name="id.family_age" class="form-control" placeholder="Enter Age" size="5">
<input type="text" ng-model="choice.qualification" name="id.family_qualification" class="form-control" placeholder="Enter Qualification" size="15">
<br/><button ng-show="$last" ng-click="addNewChoice()" class="btn btn-success">Add another member</button>
<button ng-show="$last" ng-click="removeChoice()" class="btn btn-danger">Remove field</button>
</div>
</div>
You have had an error in your initialisation of your app. The empty array in angular.module('validationApp', []). This array is the list of modules myApp depends on:
var validationApp = angular.module('validationApp',[]);
Further information in the docs.
// create angular app
var validationApp = angular.module('validationApp', []);
// create angular controller
validationApp.controller('mainController', function($scope) {
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({id:'choice' + newItemNo});
};
$scope.showChoiceLabel = function(choice) {
return choice.id === $scope.choices[0].id;
};
$scope.removeChoice = function() {
if($scope.choices.length > 1) {
var newItemNo = $scope.choices.length - 1;
$scope.choices.pop();
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="validationApp" ng-controller="mainController">
<div class="form-group" data-ng-repeat="choice in choices">
<label for="choice" ng-show="showChoiceLabel(choice)">Family Details</label>
<input type="text" ng-model="choice.name" name="id.family_name" class="form-control" placeholder="Enter Family Memeber Name" size="20">
<input type="text" ng-model="choice.relation" name="id.family_relation" class="form-control" placeholder="Enter Relation" size="15">
<input type="text" ng-model="choice.age" name="id.family_age" class="form-control" placeholder="Enter Age" size="5">
<input type="text" ng-model="choice.qualification" name="id.family_qualification" class="form-control" placeholder="Enter Qualification" size="15">
<br/><button ng-show="$last" ng-click="addNewChoice()" class="btn btn-success">Add another member</button>
<button ng-show="$last" ng-click="removeChoice()" class="btn btn-danger">Remove field</button>
</div>
</div>

Using ng-model on two inputs, same value

I'd like to use ng-model on input that receive a value of an other input ...
My code doesn't work and I don't understand why, is that possible to set ng-model to an input with Angular values?
My code
var BottomApp = angular.module('BottomApp', []);
BottomApp.controller('SeoArticle', ['$scope', function($scope) {
$scope.seoTitle = document.getElementById('title').value;
$scope.createSeoUrl = function(string){
var string;
string = string.replace(/'+/g, '');
string = string.replace(/"+/g, '');
return string.replace(/\s+/g, '-');
};
}]);
<div ng-controller="SeoArticle">
<input type="text" id="title" name="article[title]" class="form-control" placeholder="title" ng-model="seoTitle">
<input type="text" name="article[seo_title]" value="{{seoTitle2}}">
<input type="text" name="article[seo_url]" value="{{seoUrl2}}">
<div class="ui-block-title"><h5>{{seoTitle}}</h5></div>
<input type="text" id="title" class="form-control" placeholder="title" value="{{seoTitle}}" ng-model="seoTitle2">
<input type="text" id="seo_url" class="form-control" placeholder="seo_url" value="{{createSeoUrl(seoTitle)}}" ng-model="seoUrl2">
<div class="panel">
<div class="seo-overview">
<p class="seo-overview-title">{{seoTitle}}</p>
<p class="seo-overview-url">{{createSeoUrl(seoTitle)}}</p>
</div>
</div>
</div>
:
Here's a working Plunker.
I have added the ng-app call to the body tag
<body ng-app="BottomApp">
and removed the string variable declaration from createSeoUrl.
Edit: I don't think you can do it within the DOM. You should use a watcher. See the updated Plunker.
$scope.$watch("seoTitle", function(newValue) {
$scope.seoTitle2 = newValue;
$scope.seoUrl2 = $scope.createSeoUrl(newValue);
})
<input type="text" id="title" class="form-control" placeholder="title" ng-model="seoTitle2">
<input type="text" id="seo_url" class="form-control" placeholder="seo_url" ng-model="seoUrl2">

Angular JS form validation does not seem to work

Can someone please tell me why my validations are not working. I followed many blogs and can't seem to debug it on my own.
<body data-ng-app="testapp">
<div data-ng-controller="testCtrl">
<h1>Test {{name}}!!</h1>
<form name="loginForm" action="login" novalidate>
<input type="email" name="email" placeholder="email" required/>
<input type="password" name="password" placeholder="password" required/>
<button type="submit" ng-disabled="loginForm.$invalid">Login</button>
<p ng-show="loginForm.$invalid">Please fix your form.</p>
<p ng-show="loginForm.email.$invalid">Please fix your email.</p>
<p ng-show="loginForm.password.$invalid">Please fix your password.</p>
</form>
</div>
<script>
var testapp = angular.module('testapp', []);
var testCtrl = function($scope) {
$scope.name = 'validation';
};
</script>
http://jsfiddle.net/xFnx8/3/
In order for Angular to track changes on form inputs, they need to be defined as ng-model properties on the scope.
So, your demo will work if you add the appropriate ng-model attributes:
<body data-ng-app="testapp">
<div data-ng-controller="testCtrl">
<h1>Test {{name}}!!</h1>
<form name="loginForm" action="login" novalidate>
<input type="email" name="email" ng-model="email" placeholder="email" required/>
<input type="password" name="password" ng-model="passowrd" placeholder="password" required/>
<button type="submit" ng-disabled="loginForm.$invalid">Login</button>
<p ng-show="loginForm.$invalid">Please fix your form.</p>
<p ng-show="loginForm.email.$invalid">Please fix your email.</p>
<p ng-show="loginForm.password.$invalid">Please fix your password.</p>
</form>
</div>
<script>
var testapp = angular.module('testapp', []);
var testCtrl = function($scope) {
$scope.name = 'validation';
};
</script>
Here is a working fiddle.
http://jsfiddle.net/6DzR5/
Yo, I fixed your fiddle.
You need to add your inputs as ng-model:
<input type="email" name="email" placeholder="email" data-ng-model="email" data-ng-required="true"/>
<input type="password" name="password" placeholder="password" data-ng-model="password" data-ng-required="true"/>
You must add an ng-model to your inputs so the form validation of angular can kick in.
Javascript
var testapp = angular.module('testapp', []);
var testCtrl = function ($scope) {
$scope.name = 'validation';
$scope.user = {};
};
HTML modification
<input type="email" name="email" placeholder="email" ng-model='user.email' required/>
<input type="password" name="password" placeholder="password" ng-model='user.password' required/>
Working demo

Resources