What is the use of angular.copy in this situation? - angularjs

I am referring to this code on form posting as coresponding to angular documentation on simple form.
What is the use of angular.copy over here? it seems that the code still working fine in the case where angular.copy being removed.
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="update(user)" value="Save" />
</form>
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
</script>

angular.copy() to make a deep copy of the contact object. The reason for this is that user is being overwritten ( you can see by using debugger point ).
As can be read here angular.copy() performs a deep copy (cf. "clone") of the argument - essentially creating a new object - whereas using the assignment operator = just assigns reference's.
Thus in the latter case, if you we're to change something in $scope.master you would also change context.

Related

Not able to fire angular function (John Papa style)

Here's the form in html:
<form ng-submit="vm.setTest(test)">
<input type="text" ng-model="test" required />in USD
<input type="submit" value="Submit">
</form>
Here's the JavaScript:
var vm = this;
vm.setTest = setTest;
function setTest(test) {
alert(test);
}
Please note, that no $scope involved and should not be.
you will have to declare setTest like this
vm.setTest(test) {
alert(test);
}
Figure out. This is how now html looks:
<form ng-submit="testController.setTest(test)">
<input type="text" ng-model="test" required />in USD
<input type="submit" value="Submit">
</form>

AngularJs - push Object in array

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>

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

Resetting with angular in an Ionic application

I am trying to make a reset button for my cost estimator I am building using Ionic Framework. Now I have a simple reset from when It was a web app but obviously that does not work with Ionic.
I know i have to use Angular and add a controller etc but I am a rookie when it comes to Angular/Ionic and need some help.
Here is my code for current reset
HTML:
<div><button class="button button-block button-stable" id="resBtn" value="Reset">Reset</button></div>
JS:
//Reset Button//
document.forms[0].addEventListener('reset', function() {
document.getElementById('result').innerHTML = '';
document.getElementById('container').innerHTML = '';
document.getElementById('resultPrem').innerHTML = '';
document.getElementById('containerPrem').innerHTML = '';
});
It is resetting this:
<div id="priceBlock">
<h2 class="preText" > Standard = <span id="price"></span></h2>
<h3 id="container">&nbsp</h3>
<h2 class="preText">Express = <span id="pricePrem" ></span></h2>
<h3 id="containerPrem">&nbsp</h3>
I know i will have to add something like: ng(refresh) to the button then write a .controller in the app.js but could really do with some advice how to do this.
Any help would be greatly appreciated.
Cheers
Fred
You can refer angular docs
angular form guide
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="update(user)" value="Save" />
</form>
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
</script>
note:snippent from guide

Where is this json member defined

In this code taken from angular.org:
angular.copy
<div ng-controller="Controller">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">SAVE</button>
</form>
<pre>form = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
function Controller($scope) {
$scope.master= {};
$scope.update = function(user) {
// Example with 1 argument
$scope.master= angular.copy(user);
};
$scope.reset = function() {
// Example with 2 arguments
angular.copy($scope.master, $scope.user);
};
$scope.reset();
}
</script>
I can't determine where the json member is being defined. I've seen this in many of the examples on the site. What does it evaluate to?
it's a filter and it is part of angular's code - github
function jsonFilter() {
return function(object) {
return toJson(object, true);
};
}

Resources