AngularJS: Target a form with Controller As syntax in an object - javascript

Note: I did look around here on SO for solutions, yet no one had the additional issue of the function being in an object.
I have a form in my Angular JS app:
<div ng-app="plunker">
<div ng-controller="PMTController as pmt">
<form name="myForm">
<div class="form-group">
<input type="text" class="form-control" />
</div>
<button class="btn btn-primary" ng-click="pmt.search.resetSearchForm()">Reset</button>
</form>
</div>
</div>
Further, I have a controller with an object:
app.controller('PMTController', function($log) {
var _this = this;
_this.search = {
resetSearchForm: function () {
$log.debug('test');
// how to target the form?
}
};
})
My ng-click works, as the log.debug works. But no amount of tweaking to target the form so that I can reset the entire thing (empty all the fields) works.
I can do $window.myForm.reset(); but how could I do this from angular?
Note please my main issue/question is how to correctly target the form from inside that resetSearchForm function in the search object.
Note I tried changing the form name to pmt.myForm or pmt.search.myForm to no avail.
I tried $setPristine and $setUntouched() but they don't seem to clear the fields.
I know I can assign a model and assign it to all the form controls, but this is for a prototype so I'd rather do a simple reset.
I made a pen: https://codepen.io/smlombardi/pen/YWOPPq?editors=1011#0

Here is my take on your codepen that will hopefully resolve the issue:
https://codepen.io/watsoncn/pen/YWOXqZ?editors=1011
Explanation:
Angular's documentation provides an example of a "Form Reset" button, but you can apply the same logic towards resetting after submission:
Documentation:https://docs.angularjs.org/guide/forms
with a plunker:
Live Example:https://plnkr.co/edit/?p=preview
The example shows the use of Angular's copy method that creates a deep copy of whatever you pass it as a parameter and assigns it to the ng-model that is put on a particular input field. In this case they simply pass it an empty master object.
You need to make sure to add an ng-model attribute to your inputs, then create a reset function that can run after submission. Another common option would be to simply set each input's ng-model to empty strings in the submission function, such as $scope.inputModel = ""
Is this what you were hoping for? I might have misunderstood the question. I will happily take another crack at it if there is still confusion.

To get the form in your controller you just need to name your form this way:
<form name="pmt.myForm">
Here's a complete demo:
(function() {
"use strict";
angular
.module('plunker', [])
.controller('PMTController', PMTController);
PMTController.$inject = ['$log'];
function PMTController($log) {
var _this = this;
_this.model = {};
_this.search = {
resetSearchForm: function() {
console.log(_this.myForm); // -> Form reference
_this.model = {};
}
};
}
})();
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body ng-controller="PMTController as pmt">
<div class="col-md-12">
<form name="pmt.myForm">
<div class="form-group">
<input type="text" ng-model="pmt.model.example" class="form-control" />
<input type="text" ng-model="pmt.model.example2" class="form-control" />
<input type="text" ng-model="pmt.model.example3" class="form-control" />
</div>
<button class="btn btn-primary" ng-click="pmt.search.resetSearchForm()">Reset</button>
</form>
<hr> All fields:
<pre ng-bind="pmt.model | json"></pre>
</div>
</body>
</html>

Related

on-click event does not make the other field editable in one-click?

<!--Below is the html code-->
<div ng-init="InitializeFields()">
<input type="text" on-click="makeOtherReadOnly('1')"
readonly="show_or_not_first"/>
<input type="text" on-click="makeOtherReadOnly('2')" readonly="show_or_not_second"/>
</div>
// Now inside javascript
$scope.makeOtherReadOnly=function(number){
if(number==='1'){
show_or_not_second=true;
show_or_not_first=false;
show_or_not_second=true;
}else if(number==='2'){
show_or_not_first=true;
show_or_not_second=false;
}
};
$scope.Initializer=function(){
show_or_not_first=false;
show_or_not_second=false;
}
$scope.Initializer();
the problem that I am facing is as I click on the input field, it should turn the other field to readonly after pafe gets loaded and we have either field clicked, but it requires two click...
Every help is appreciated.
Try changing on-click to ng-click.
You need to correct few things ion your code :
change on-click to ng-click, So your function can be called from HTML.
Change readonly to ng-readonly, So you can utilize $scope property
In your ng-init, I guess you need to call Initializer() method to initialize default value.
Further just to make 2 input box readonly, you can chieve this by 1 flag. and no string comparison.
Simple Demo :
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.makeOtherReadOnly = function(boolValue) {
console.log(boolValue);
$scope.data.first = boolValue;
};
$scope.Initializer = function() {
$scope.data = {
first: false
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-init="Initializer()">
First: <input type="text" ng-click="makeOtherReadOnly(false)"
ng-readonly="data.first" />
Second: <input type="text" ng-click="makeOtherReadOnly(true)"
ng-readonly="!data.first" />
</div>
</div>
There are two scopes here
javascript and angular
sometimes inside ng-click, javqascript function don't work
so change on-click to ng-click.

How to clear a form within an angular app that appears on click?

I have seen several tutorials on how to clear angular (version 1.4.0) forms, however.. none of them seem to work in my case. I am puzzled. The following form is display: none; to begin with, but comes into existence when the 'Add' button is clicked.
<div id="..." class="displayNone ...">
<form class="..." name="addFooForm">
<div class="...">
<div class="row">
<div class="col-md-offset-3 col-md-6">
<br>
<div class="form-group">
<label>Foos</label>
<input type="text" class="..." id="..." ng-model="foo.value">
</div>
</div>
</div>
</div>
<div class="...">
...
<input type="button" value="Cancel" class="..." ng-click="resetAddFooForm()">
</div>
</form>
</div>
And in my controller, I have the following.
$scope.resetAddFooForm = function () {
// XXX:
console.log('about to reset the form');
$scope.foo = {};
// $scope.addFooForm.$setValidity();
// $scope.addFooForm.$setPristine();
// $scope.addFooForm.$setUntouched();
};
But, although the console.log message is being displayed. The form field is not being cleared. I have have even tried doing it directly as follows.
$scope.resetAddFooForm = function () {
// XXX:
console.log('about to reset the form');
$scope.fooVal = '';
// $scope.addFooForm.$setValidity();
// $scope.addFooForm.$setPristine();
// $scope.addFooForm.$setUntouched();
};
.. with the above html modified as follows.
<div class="form-group">
<label>Foos</label>
<input type="text" class="..." id="foo" ng-model="fooVal">
</div>
But nothing seems to be working. Is it perhaps because the $scope is different due to the form being dynamically inserted? But then how do I tackle that?
I just want to be able to clear the fields (and also clear the angular properties like dirty/pristine, etc) of this dynamically generated form.
Update:
I was able to send this from the html back to the controller, and then use it do what I wanted. So it appears that the problem may actually be to do with differing scopes.
<div class="...">
...
<input type="button" value="Cancel" class="..." ng-click="resetAddFooForm(this)">
</div>
And then have this retrieved the controller.
$scope.resetAddFooForm = function (elem) {
elem.foo = {};
elem.$setValidity();
elem.$setPristine();
elem.$setUntouched();
};
Any hints? Why do I need to send this, when I should really be able to simply use $scope. Why doesn't that work?
Initially declare empty object on your controller
$scope.foo = {}
then try empty it on reset
You can manually reset fields value.

Submit updated ng-model via JavaScript

I want to submit text stored in a ng-model via JavaScript. I have the following code:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<body>
<div ng-app>
<div ng-controller="Ctrl">
<form ng-submit="submit()">Enter text here:
<input type="text" ng-model="in" name="text" />
<input type="submit" id="submit" value="Submit" /> <pre>Last input: {{active}}</pre>
</form>
</div>
</div>
<script>
function Ctrl($scope, $http) {
$scope.active = "none";
$scope.in = "enter input here";
$scope.submit = function () {
$http.post("do_something.php",{sometext:$scope.in})
.then(function(response) {
$scope.active = response.data;
});
};
}
</script>
</body>
</html>
I want to write an extension, that enters text into the input field and submits it.
I use JavaScript to access the elements which have the ng-model, and change their value:
document.getElementsByTagName("input")[0].value="hello";
this only changes the text in my input field, but does not affect the actual in-variable. when submitting the form via
document.getElementsByTagName("input")[1].click()
The submitted input is not the input it previously changed to, but instead the old input - not visible any more.
I think this is because changing values via Javascript does not change the ng-model according to the input fields value.
How can I do this properly?
This is not very good idea to modify Angular models from outside of the Angular app itself. But given that you have a good reason for that you can do it like this:
var input = angular.element(document.getElementsByTagName("input")[0]);
var model = input.controller('ngModel');
model.$setViewValue('New value');
model.$render();
input.parent('form').triggerHandler('submit');
By working with ngModelController directly you have a benefit that you don't have to know the actual model name. You just use ngModelController API. Another benefit is that you don't need to do error prone stuff like document.getElementsByTagName("input")[1].click(). Instead, just directly trigger function used by ngSubmit directive.
Here is a quick demo:
function Ctrl($scope) {
$scope.in = "enter input here";
$scope.submit = function() {
alert('Value submitted: ' + $scope.in);
};
}
function updateModel() {
var input = angular.element(document.getElementsByTagName("input")[0]);
var model = input.controller('ngModel');
model.$setViewValue('New value');
model.$render();
input.parent('form').triggerHandler('submit');
}
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<div ng-app ng-controller="Ctrl">
<form ng-submit="submit()">
Enter text here:
<input type="text" ng-model="in" name="text" />
<input type="submit" id="submit" value="Submit" />
</form>
</div>
<hr>
<p>Set model from outside of the Angular app.</p>
<button onclick="updateModel()">Set model</button>
You are going out from the angular environment... That should be avoided, but, sometimes it's needed: in that case you need to manually trigger the $digest cycle, this is an example:
function onNoNgClick() {
var $scope = angular.element(document.getElementById('TestForm')).scope();
$scope.$apply(function() {
$scope.value = 'FOOBAZ';
return $scope.submitRequest();
});
}
function TestCtrl($scope) {
$scope.value = 'Initial Value';
$scope.submitRequest = function() {
console.log('sendData', $scope.value);
};
}
angular
.module('test', [])
.controller('TestCtrl', TestCtrl);
document.addEventListener('DOMContentLoaded', function() {
return document.getElementById('NoNG').addEventListener('click', onNoNgClick);
});
.no-ng {
padding: 1em;
border: 1px solid green;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app='test'>
<div ng-controller="TestCtrl">
<form ng-submit="submitRequest()" name="testRequest" id="TestForm">
<input type="text" ng-model="value" />
<button type="submit">Submit</button>
</form>
</div>
</section>
<div class="no-ng"><button id="NoNG">SetText: FOOBAZ</button></div>

Access "calling scope" and strange behaviour

I have a simple snippet of code :
function SomeCtrl($scope) {
$scope.modify = function(value) {
$scope.something = "Hello";
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div ng-controller="SomeCtrl">
<div ng-repeat="toto in [1,2,4,5]">
<input ng-model="something" />
<input ng-model="something" />
<button ng-click="modify()">Modify</button>
</div>
</div>
</div>
Does anyone can explain how I could change it so the modify() function only change the textfields inside the scope of the button I click ?
I also don't get why only the text fields which have not been edited are modified by the function.
Thank you very much
This is because ng-repeat creates it's own scope. Using prototypal inheritance. By declaring ng-model you're creating a new field on that new scope.
But this will work for what you're trying to do.
<div ng-repeat="toto in [1,2,4,5]" ng-init="something = {}">
<input ng-model="something.hi" />
<input ng-model="something.hi" />
<button ng-click="modify(something)">Modify</button>
</div>
</body>
.controller('ctrl', function ($scope) {
$scope.modify = function (something) {
something.hi = "hello";
}
})
In this case you are just pushing out on screen the same info for times, meanwhile binding everything to the same variable. You can just simply create array and bind every input line to appropriate array element. And by pressing "modify" button, pass parameter, witch array element must be changed.
function SomeCtrl($scope) {
$scope.something = [];
$scope.modify = function(toto) {
$scope.something[toto] = toto;
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div ng-controller="SomeCtrl">
<div ng-repeat="toto in [1,2,4,5]">
<input ng-model="something[toto]" />
<input ng-model="something[toto]" />
<button ng-click="modify(toto)">Modify</button>
</div>
</div>
</div>

Undefined - Trying to pass a value from a form to a JS function using jQuery and getting it very wrong

I'm trying to learn how to use JS in order to create a unit converter for a site I'm working on.
I did have intentions of trying to accomplish it using PHP but someone pointed out how inefficient it would be and so I'm now trying to learn JS to carry out the same tasks.
I've written a very small test function to add two numbers, it worked fine. I then adjusted it slightly to take in a few more params and to check a couple of conditions, again that worked fine - I created a new object and passed the variables in directly.
I now need to pass the values from the form that I have into this function in order to compute the sum and output the result. I keep getting an error of 'undefined'. I've googled and read but can't seem to find a solution.
so far I have:
<script type="text/javascript">
function Convert(from, to, units){
this.from = $("#from").val();
this.to = $("#to").val();
this.units = $("#units").val();
}
Convert.prototype.convertThem = function(){
if(this.from == "degC"){
if(this.to == "degF"){
return this.units * 347956757524;
}
}
}
calcTempTest = new Convert(this.from, this.to, this.units);
alert(calcTempTest.convertThem());
console.log(calcTempTest);
</script>
Could anyone tell me what I'm doing wrong please? The 'to','from' and 'units' are the id's from the form.
The Form:
<div class="form">
<label for="units">Units:</label>
<input type="text" name="units" id="units" class="required digits" />
</div>
<div class="form">
<label for="from">Convert From:</label>
<select name="from" id="from">
<option value="from">-Select an Option-</option>
</select>
</div>
<div class="form">
<label for="to">Convert Into:</label>
<select name="to" id="to">
<option value="to">-Select an Option-</option>
</select>
</div>
<div class="form">
<label> </label>
<input type="submit" name="submit" value="Convert!" />
</div>
many thanks.
Explanation
Your select selected option value onLoad both are "from" and "to". Since these are not equal to "degF" and "degC", your assignments won't go on, the resulting variable will be undefined since no value will be asssigned to it.
Solution
Add several option to your select or change their default value. I also added a default value to the input.
HTML
<input type="text" name="units" id="units" value="12" class="required digits" />
<option value="degC">-Select an Option-</option>
<option value="degF">-Select an Option-</option>
EDIT
I have added a JSFiddle here which executes the script on the button click with the following modifications to JavaScript:
NOTE: I also added the real formula.
JavaScript/jQuery
$('input[name="submit"]').click(function () {
var c = new Convert();
alert(c.convertThem());
});
function Convert() {
this.from = $("#from").val();
this.to = $("#to").val();
this.units = $("#units").val();
}
Convert.prototype.convertThem = function () {
if (this.from == "degC") {
if (this.to == "degF") {
return this.units * 1.8 + 32;
}
}
}
I think when you create the convert object you're trying to pass variables that don't exist:
calcTempTest = new Convert(this.from, this.to, this.units);
I'm pretty sure this stands for window at that point and windw.from is undefined. You don't seem to be doing anything with these values anyway so you could change it to:
calcTempTest = new Convert();
Maybe the following answer could help you out with what this stands for in JS: Prototypical inheritance - writing up
Here is some minimally working code:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
</head>
<body>
<div class="form">
<label for="units">Units:</label>
<input type="text" name="units" id="units" class="required digits" />
</div>
<div class="form">
<label for="from">Convert From:</label>
<select name="from" id="from">
<option value="degC">degC</option>
</select>
</div>
<div class="form">
<label for="to">Convert Into:</label>
<select name="to" id="to">
<option value="degF">degG</option>
</select>
</div>
<div class="form">
<label for="output">Output:</label>
<input type="text" id="output" />
</div>
<div class="form">
<label> </label>
<input type="submit" id="subm" name="submit" value="Convert!" />
</div>
<script type="text/javascript">
(function () {
function Convert(from, to, units) {
// when convert is created set a reference to the input elements
this.$from = $("#from");
this.$to = $("#to");
this.$units = $("#units");
this.$output = $("#output");
}
Convert.prototype.convertThem = function () {
// this.$... is a jQuery object containing the input elements
if (this.$from.val() == "degC") {
if (this.$to.val() == "degF") {
this.$output.val( this.$units.val() * 347956757524);
}
}
}
calcTempTest = new Convert();
$("#subm").on("click", null, null, function () {
calcTempTest.convertThem();
});
})();//anonymous funciton, no variables in global scope
</script>
</body>
</html>
There are several issues with your code. Most of them have been resolved in the accepted answer, but I wanted to provide some more insights that would help you create more reusable code in the future.
Since I have already created a jsfiddle with my own example, it will be a shame to let it go to waste so I will post it anyway with some comments.
Using constructor parameters
function Convert(from, to, units, res){
this.from = from;
//etc...
}
Passing parameters to an object's constructor (and using them) makes it more reusable. You did not use the passed parameters and the selected answer used what I assume was your original solution (hard-coding the element values into the object upon construction).
This way you can have multiple instances of the converter on the same page, you can put its code in an external file as it gets more complex and only put the instantiation logic in the page itself (if your page structure changes, there is no need to change the external file, just update the provided constructor parameters).
Storing node references instead of values
The other thing I wanted to point out is the way the calculation is done.
Your implementation requires a new object to be created for each calculation. I find it much better to create a single Converter and obtain the values only when required. That it the reason I stored a reference to the form field DOM nodes and did not store their values.
$("#btnConvert").click(calcTempTest.convertThem.bind(calcTempTest));
I used bind(...) in the click attachment to preserve the object's scope.
Good luck!

Categories