Trying to understand angular.copy - javascript

I'm trying to understand what angular.copy will do. I've seen one example in Angular js doc but not able to figure out why reset button is not working after filling all the text fields and clicking on save button. But it works when we click on reset button before clicking on Save.Can someone please explain.Thanks in advance
index.html:
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
<label>Name: <input type="text" ng-model="user.name" /></label><br />
<label>Age: <input type="number" ng-model="user.age" /></label><br />
Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label>
<label><input type="radio" ng-model="user.gender" value="female" />female</label><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.js:
angular.
module('copyExample', []).
controller('ExampleController', ['$scope', function($scope) {
$scope.master = {};
$scope.reset = function() {
// Example with 1 argument
$scope.user = angular.copy($scope.master);
};
$scope.update = function(user) {
// Example with 2 arguments
angular.copy(user, $scope.master);
};
$scope.reset();
}]);

$scope.user does not even exist before you click reset.

Angular copy method only allocate another instance of memory to from
master to user. And Will avoid reference issues if you don't want to change user without changing master;
reference here
You problem is in $scope.user instead of just user:
Working snippet bellow:
$scope.update = function(user) {
// Example with 2 arguments
angular.copy($scope.user, $scope.master);
};
(function(angular) {
'use strict';
angular.module('includeExample', ['ngAnimate'])
.controller('ExampleController', ['$scope', '$q',
function($scope, $q) {
$scope.master = {};
$scope.reset = function() {
// Example with 1 argument
$scope.user = angular.copy($scope.master);
};
$scope.update = function(user) {
// Example with 2 arguments
angular.copy($scope.user, $scope.master);
};
$scope.reset();
}
]);
})(window.angular);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.1/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.1/angular-animate.js"></script>
<body ng-app="includeExample">
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
<label>Name: <input type="text" ng-model="user.name" /></label><br />
<label>Age: <input type="number" ng-model="user.age" /></label><br />
Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label>
<label><input type="radio" ng-model="user.gender" value="female" />female</label><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>
</body>

Related

TypeError: Attempted to assign to readonly property - when typing in a text field

I recently updated my Angular from 1.5.x to 1.6.4 and now, when I go to a form, I get the below error message whenever I try to type something up in the form/textbox:
TypeError: Attempted to assign to readonly property.
This is my controller:
mainApp.controller('newPostController', ['$scope', '$http', function($scope, $http){
$scope.post = '';
$scope.postCreated = false;
$scope.makeNewPost = function() {
$http.post('/api/post', {
title: $scope.post.title,
})
.then(function(res){
$scope.postCreated = true;
//extra code not related to the form itself...
};
}]);
My HTML looks like this:
<form ng-submit="makeNewPost()">
<div class="form-group">
<label for="title" class="control-label">Title</label>
<input type="text" autocomplete="off" class="form-control" ng-model="post.title" id="title" required="required">
</div>
<input type="submit" value="Submit">
</form>
I looked this error up and everything I am seeing has nothing to do with what my set up is like.
Please help me out on this. I don't know where to go from here.
Thanks
Try this...
you have initialized $scope.post = ''; as a string. But that should be $scope.post = {}; an object.
var mainApp = angular.module('app', []);
mainApp.controller('newPostController', ['$scope', '$http', function($scope, $http) {
$scope.post = {};
$scope.postCreated = false;
$scope.makeNewPost = function() {
console.log($scope.post.title);
$http.post('/api/post', {
title: $scope.post.title,
})
.then(function(res) {
$scope.postCreated = true;
//extra code not related to the form itself...
});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app='app' ng-controller='newPostController'>
<form ng-submit="makeNewPost()">
<div class="form-group">
<label for="title" class="control-label">Title</label>
<input type="text" autocomplete="off" class="form-control" ng-model="post.title" id="title" required="required">
</div>
<input type="submit" value="Submit">
</form>
</div>

Angular: Ng-show only while off Input Field in Form

https://jsfiddle.net/jzhang172/xu93yubL/
The particular issue is in my E-mail input field.
Is it possible to only display the ng-show message after the field is validated and when the user is not inside the input field?
In other words, I want the ng-show message to disappear if the user is on the input field.
I've tried a number of combinations of logic and haven't been able to get it to work:
(function(angular) {
'use strict';
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function(form) {
if (form) {
form.$setPristine();
form.$setUntouched();
}
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
})(window.angular);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<body ng-app="formExample">
<div ng-controller="ExampleController">
<form name="form" class="css-form" novalidate>
Name:
<input type="text" ng-model="user.name" name="uName" required="" />
<br />
<div ng-show="form.$submitted || form.uName.$touched">
<div ng-show="form.uName.$error.required">Tell us your name.</div>
</div>
E-mail:
<input type="email" ng-model="user.email" name="uEmail" required="" />
<br />
<div ng-show="form.$submitted || form.uEmail.$touched">
<span ng-show="form.uEmail.$error.required" style="background:red;">Tell us your email.</span>
<span ng-show="form.uEmail.$error.email"style="background:red;">This is not a valid email.</span>
</div>
</form>
</div>
</body>
You can use ngFocus and ngBlur directives to achieve desired result...
Just set some variable false on ngFocus and set true with ngBlur and add that variable into your ngShow condition...
<input type="email" ng-model="user.email" name="uEmail" required="" ng-focus="showEmailValidationMsg = false;" ng-blur="showEmailValidationMsg = true;"/>
<br />
<div ng-show="(form.$submitted || form.uEmail.$touched) && showEmailValidationMsg">
<span ng-show="form.uEmail.$error.required" style="background:red;">Tell us your email.</span>
<span ng-show="form.uEmail.$error.email"style="background:red;">This is not a valid email.</span>
</div>
and here is working JSFIDDLE...

Angularjs $setPristine not working with controller as syntax

$setPristine works alright when referenced with $scope but doesn't seem to work with 'controller as syntax'
In View:
<h2>With Controller as syntax</h2>
<div ng-controller="FirstCtrl as first">
<form name="form1" id="form" novalidate>
<input name="name" ng-model="first.data.name" placeholder="Name" required/>
<button class="button" ng-click="first.reset()">Reset</button>
</form>
<p>Pristine: {{form1.$pristine}}</p>
<p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
<hr>
<h2>With $scope</h2>
<div ng-controller="SecondCtrl">
<form name="form1" id="form" novalidate>
<input name="name" ng-model="data.name" placeholder="Name" required/>
<button class="button" ng-click="reset()">Reset</button>
</form>
<p>Pristine: {{form1.$pristine}}</p>
<p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
In app.js:
var app = angular.module('plunker', []);
app.controller('FirstCtrl', function() {
'use strict';
var vm = this;
vm.data = { "name": ""};
vm.reset = function() {
vm.data.name = "";
vm.form1.$setPristine();
}
});
app.controller('SecondCtrl', function($scope) {
'use strict';
$scope.data = { "name": ""};
$scope.reset = function() {
$scope.data.name = "";
$scope.form1.$setPristine();
}
});
Here is the plunker: http://plnkr.co/edit/VcgZx3?p=preview
Even if you use controller as syntax, the form and other attributes are still bound to the scope not to the controller instance so you still have to use $scope.form1.$setPristine(); to set the form's state.
var app = angular.module('my-app', [], function() {})
app.controller('FirstCtrl', function($scope) {
'use strict';
var vm = this;
vm.data = {
"name": ""
};
vm.reset = function() {
vm.data.name = "";
$scope.form1.$setPristine();
}
});
app.controller('SecondCtrl', function($scope) {
'use strict';
$scope.data = {
"name": ""
};
$scope.reset = function() {
$scope.data.name = "";
$scope.form1.$setPristine();
}
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<div ng-app="my-app">
<h2>With Controller as syntax</h2>
<div ng-controller="FirstCtrl as first">
<form name="form1" id="form" novalidate>
<input name="name" ng-model="first.data.name" placeholder="Name" required/>
<button class="button" ng-click="first.reset()">Reset</button>
</form>
<p>Pristine: {{form1.$pristine}}</p>
<p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
<hr/>
<h2>With $scope</h2>
<div ng-controller="SecondCtrl">
<form name="form1" id="form" novalidate>
<input name="name" ng-model="data.name" placeholder="Name" required/>
<button class="button" ng-click="reset()">Reset</button>
</form>
<p>Pristine: {{form1.$pristine}}</p>
<p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
</div>
An alternative to using Arun's suggestion of accessing the form through $scope is simply to ensure the form is accessible through the controller.
To do this all you have to do is change your HTML for the 'controller as' version very slightly. Change the form's name to include the controller object, also change any references to the form from the template to include the controller variable:
<h2>With Controller as syntax</h2>
<div ng-controller="FirstCtrl as first">
<form name="first.form1" id="form" novalidate>
<input name="name" ng-model="first.data.name" placeholder="Name" required/>
<button class="button" ng-click="first.reset()">Reset</button>
</form>
<p>Pristine: {{first.form1.$pristine}}</p>
<p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
<hr>
Your Javascript will now run unchanged.
I think an even easier way to accomplish this is to provide the form controller as a parameter to the reset() function:
…
<button class="button" ng-click="reset(form1)">Reset</button>
…
and change the reset() function slightly, so that it uses the supplied parameter:
$scope.reset = function(form) {
$scope.data.name = "";
form.$setPristine();
}
You can use $setPristine without $scope:
<form ng-submit="$ctrl.save()" name="$ctrl.myForm">
And in your controller:
var $ctrl = this;
...
$ctrl.myForm.$setPristine();
$ctrl.myForm.$setUntouched();
It works for me. (AngularJS v1.5.7)

Controller and input form html use var Javascript

I use the angularjs framework, I created an form.html and a controller.js with a variable that retrieves the SSID of a box.
How to automatically assign the value of the variable in the form.
This is an input field.
When launching the application, the form should display the SSID automatically without the user needing to do so.
Thank you kindly help me.
'use strict';
angular.module('djoro.controllers')
.controller('WifiSmartConfigCtrl', function ($scope, $window, $ionicPlatform) {
$scope.getSSID = function () {
var onSuccess = function (SSID) {
document.write(SSID);
};
var onFail = function () {
};
$ionicPlatform.ready(function () {
$window.cordova.plugins.Smartconfig.getSSID(onSuccess, onFail);
});
};
});
<ion-pane>
<ion-content ng-controller="WifiSmartConfigCtrl">
<form novalidate class="simple-form">
<fieldset>
<legend>WI-FI</legend>
<div class="list input-fields">
<label class="item item-input">
<span class="input-label">SSID :</span>
<input type="text" name="test" value="getSSID()" required show-hide-input>
</label>
<label class="item item-input" show-hide-container>
<span class="input-label">Password :</span>
<input type="text" name="password" required show-hide-input>
</label>
</div>
</fieldset>
</form>
</ion-content>
</ion-pane>
use the ng-model directive, it's exactly it's purpose :
'use strict';
angular.module('djoro.controllers')
.controller('WifiSmartConfigCtrl', function($scope, $window, $ionicPlatform) {
$scope.SSID = {};
$scope.getSSID = function() {
var onSuccess = function(SSID) {
$scope.SSID = SSID;
};
var onFail = function() {};
$ionicPlatform.ready(function() {
$window.cordova.plugins.Smartconfig.getSSID(onSuccess, onFail);
});
};
});
and in your view :
<input type="text" name="test" ng-model="SSID" required show-hide-input>
You need to add an ng-model to the input field like so:
<label class="item item-input">
<span class="input-label">SSID :</span>
<input type="text" name="test" ng-model="SSID" required show-hide-input>
</label>
then in your controller assign the value of SSID on the $scope:
$scope.SSID = [some_value]
see this plnkr
As you can see I have assigned the value of SSID manually, you can add it dynamically by assigning it in the callback of your function like so:
$scope.SSID = {}
var onSuccess = function (SSID) {
document.write(SSID);
$scope.SSID = SSID
};

AngularJS binding checkboxes to model property

I have an AngularJS app with a list of users with an 'Edit' button beside each user. Each user has a number of subjects associated with them. When I click on 'Edit', it opens a form in which you can edit user details, and select associated subjects from a list of checkboxes. I'm trying to figure out how to bind the subject checkboxes so that the subjects which the
user is already associated with are checked, and the rest are unchecked. Any suggestions appreciated.
My HTML:
<form name="UserEditForm">
Name: <br /> <input type="text" name="name" ng-model="user.name"> <br />
{{name}}
Email: <br /> <input type="text" name="name" ng-model="user.email"> <br />
{{email}}
<div class="control-group">
<label class="control-label" for="inputSubjects">Subjects:</label>
<div class="form-group">
<label ng-repeat="subject in subjects" class="checkbox">
<input type="checkbox" ng-checked="{user.subjects}" name="selectedSubjects[]" value="{{subject.id}}" ng-model="subject.selected"> {{subject.name}}
</label>
</div>
<br />
<a ng-click="updateUser()" class="btn btn-small btn-primary">Save Changes</a>
</form>
My UserEditCtrl:
angular.module('myApp.controllers')
.controller('UserEditCtrl', ['$scope', '$routeParams','SubjectsFactory', 'UserFactory', '$location',
function ($scope, $routeParams, SubjectsFactory, UserFactory, $location) {
// callback for ng-click 'updateUser':
$scope.updateUser = function () {
$scope.user.subjects = $scope.selection;
UserFactory.update($scope.user);
$location.path('/users');
};
// callback for ng-click 'cancel':
$scope.cancel = function () {
$location.path('/users');
};
$scope.user = UserFactory.show({id: $routeParams.userid});
$scope.subjects = SubjectsFactory.query();
$scope.selection = [];
// helper method
$scope.selectedSubjects = function selectedSubjects() {
return filterFilter($scope.subjects, { selected: true });
};
// watch subjects for changes
$scope.$watch('subjects|filter:{selected:true}', function (nv) {
$scope.selection = nv.map(function (subject) {
return subject.id;
});
}, true);
}]);
As #jkinkead said, your code looks good, I fixed the ng-checked binding in accordance with your ng-model expression
Here's a simplified plunker : http://plnkr.co/edit/qaIBExtVbNdSXlQlbMym?p=preview
EDIT 1: I edited and improved the plunker to get closer to your case.

Categories