Cannot get value of ng-model through $scope - javascript

I am trying to get the value of the ng-model when clicking a button which triggers a function to add each ng-model value to an object. When trying to get the value of $scope.shipNameFirst, it comes up as undefined in the second example.
I've read that it's better to get the value of $scope on the view rather than passing it through the stripeBtn function, so ideally I'd like to do it that way. Hopefully this makes sense.
Can someone explain why this is not working?
Working
HTML
<input type="text" ng-model="shipNameFirst">
<input type="text" ng-model="shipNameLast">
<button type="button" ng-click="stripeBtn(shipNameFirst, shipNameLast)">Checkout with Stripe</button>
Controller
$scope.stripeBtn = function(shipNameFirst, shipNameLast){
$scope.details = {
recNameFirst: shipNameFirst,
recNameLast: shipNameLast,
}
}
Not Working
HTML
<input type="text" ng-model="shipNameFirst">
<input type="text" ng-model="shipNameLast">
<button type="button" ng-click="stripeBtn()">Checkout with Stripe</button>
Controller
$scope.stripeBtn = function(){
console.log($scope.shipNameFirst); //logging this (with $scope) comes up as undefined
$scope.details = {
recNameFirst: $scope.shipNameFirst,
recNameLast: $scope.shipNameLast,
}
}
Thanks!

Check the following code. It's working nicely.
var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope){
$scope.stripeBtn = function(){
console.log($scope.shipNameFirst);
$scope.details = {
recNameFirst: $scope.shipNameFirst,
recNameLast: $scope.shipNameLast,
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<input type="text" ng-model="shipNameFirst">
<input type="text" ng-model="shipNameLast">
<button type="button" ng-click="stripeBtn()">Checkout with Stripe</button>
</div>

Related

$scope.variable is undefined in browser console while form submit AngularJs

I want $scope.variable value in browser console but its always occur undefined.
form.htm
<form>
<p>First Name: <input type="text" name="firstName" ng-model="firstName"
required /></p>
<button ng-click="SendData()">Submit</button>
</form>
myctr.js
app.controller('myCtrl', ['$scope', '$http', 'ngCart', '$localStorage',
'$sessionStorage', '$window',
function($scope, $http, ngCart, $localStorage,
$sessionStorage, $window) {
$scope.SendData = function() {
console.log($scope.firstName)
$window.alert($scope.firstName)
};
}
]);
Possible problem is that you're using a simple string value $scope.firstName. If your input is more than one scope "deeper" in the DOM hierarchy, then your $scope.firstName and ng-model in the input become two independent variables so no wonder that you get $scope.firstName undefined. That's the typical problem with simple types and scopes inheritance. Possible ways to solve this would be:
use object to bind data between the controller and template: $ctrl.user.firstName and <input ng-model="user.firstName">.
use the "controllerAs" syntax.
Read more on this in documentation on controllers and scopes.
use the following modified code ---
var app = angular.module('myApp', ['ngStorage']);
app.controller('myCtrl', function($scope, $window,$http,$localStorage,$sessionStorage) {
$scope.SendData = function() {
console.log($scope.firstName)
$window.alert($scope.firstName)
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form>
<p>First Name: <input type="text" name="firstName" ng-model="firstName"
required /></p>
<button ng-click="SendData()">Submit</button>
</form>
</div>
Modified the answer...
As per the definition of ngModel it will try to bind to the property given by evaluating the expression on the current scope. If the property doesn't already exist on this scope, it will be created implicitly and added to the scope.
Here when submit is clicked without filling the text box $scope.firstName is undefined because firstName it is not defined in the current $scope.
If something is typed in the text box , as per the definition of ng-model a firstName property will be created implicitly and added to the scope.
Let controller be
app.controller('MainCtrl', function($scope) {
$scope.lastName='';
$scope.SendData = function() {
console.log($scope.firstName)
alert($scope.firstName)
};
$scope.CheckLast = function() {
console.log($scope.lastName)
alert($scope.lastName)
};
});
HTML
<body ng-controller="MainCtrl">
<form>
<p>First Name: <input type="text" name="firstName" ng-model="firstName"/></p>
<button ng-click="SendData()">Submit</button>
<p>Last Name: <input type="text" name="lastName" ng-model="lastName"/></p>
<button ng-click="CheckLast()">Submit</button>
</form>
</body>
Here Demo plunker you can see firstName is undefined while lastName is not as last name is initialised within the scope. and if something will be filled to firstName text box before submit the it is defined.

AngularJS data binding not working - within the controller Scope variables are not showing the entered value

I have a strange situation in which $scope variables binding do not appear to be work as expected.
Here is the HTML:
<div class="input-group" style="width:100px">
<input type="number"
class="form-control"
id="Sampling_Request_for_Current_Sampling_INPUT"
ng-model="aabbcc"
style="width:125px;text-align:center">
<span class="input-group-btn">
<button class="btn btn-default" ng-disabled="Cannot_Allocate_Yet" ng-click="Get_Sampling_Request_Details()" type="button">{{All_Labels.Common.Display}}</button>
</span>
</div>
and here is the scope function invoked upon clicking on the button:
$scope.Get_Sampling_Request_Details = function () {
console.log("$scope.aabbcc: " + $scope.aabbcc) ;
}
The variable $scope.aabbcc is initialized to 0 upon controller's loading.
Regardless what I type into the input element, I always get 0 in the console.
This scenario generally happens, If you have wrapped your HTML inside ng-if, ng-switch ng-repeat.. or some other directive that creates new child scope.
See this fiddle.
So it's a best practice to wrap your scope in some model to leverage protypical inheritance and correctly bind data to $scope.
Like : $scope.data.aabbcc = 0 and use it like ng-model ='data.aabbcc'.
See this for few minutes and Read this for complete understanding.
check this working example
<div ng-controller="MyCtrl">
Hello, {{name}}!
<input type="number" ng-model="name"/>
<button class="btn btn-default" ng-disabled="Cannot_Allocate_Yet" ng-
click="Get_Sampling_Request_Details()" type="button">test</button>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.name = 0;
$scope.Get_Sampling_Request_Details = function () {
console.log("$scope.aabbcc: " + $scope.name) ;
}
}
AngularJS controllers control the data. The scope is the binding part between the HTML (view) and the JavaScript (controller). You must define the ng-model inside a ng-controller within which its scope lies. Try this out.
<div ng-controller="myCtrl">
<div class="input-group" style="width:100px">
<input type="number"
class="form-control"
id="Sampling_Request_for_Current_Sampling_INPUT"
ng-model="aabbcc"
style="width:125px;text-align:center">
<span class="input-group-btn">
<button class="btn btn-default" ng-disabled="Cannot_Allocate_Yet" ng-click="Get_Sampling_Request_Details()" type="button">{{All_Labels.Common.Display}}</button>
</span>
</div>
</div>
<script>
var app = angular.module('Myapp', []);
app.controller('myCtrl', function($scope) {
$scope.Get_Sampling_Request_Details = function () {
console.log("$scope.aabbcc: " + $scope.aabbcc) ;
}
});
</script>
Declare an empty object in your controller section .
eg: $scope.obj = {};
And use like ng-model="obj.key_name" in your html. It will work.

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>

Update Textarea value with ID instead of using ng-model in AngularJs

I can use the below code snippets to update the value of one textarea with another simultanoeusly
<div ng-app="myApp">
<div ng-controller="myCtrl">
<input id="id1" type="text">
<input id="id2" type="text">
</div>
</div>
Script file:
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', ['$scope', function($scope){
$scope.text1 = '';
}]);
Is there a way I can use the ID to update the value simultanously instead of the ng-model property. Thank you!!!
You can try to use $watch:
$scope.$watch('text1', function () {
document.getElementById('id2').value = $scope.text1;
});

Argument '' is not a function, got undefined in Kendo ( AngularJS )

I want to make a Kendo grid with 4 tabstrips, 4 children grids, 5 controllers, first is parent, others are children. Here is a part of code, with one parent and one child controller. Problem is that all the time I got an error "Argument '' is not a function, got undefined" Where should I define it? Everything is stored locally so the preview is not possible
Check this out:
http://fdietz.github.io/recipes-with-angular-js/controllers/sharing-models-between-nested-controllers.html
You don't nest the controllers in your javascript. This is from that link:
var app = angular.module("MyApp", []);
app.controller("MyCtrl", function($scope) {
$scope.name = "Peter";
$scope.user = {
name: "Parker"
};
});
app.controller("MyNestedCtrl", function($scope) {
});
Instead, you nest the controllers in your markup. I don't see where you are binding the controllers in your markup, btw.
<body ng-app="MyApp">
<div ng-controller="MyCtrl">
<label>Primitive</label>
<input type="text" ng-model="name">
<label>Object</label>
<input type="text" ng-model="user.name">
<div class="nested" ng-controller="MyNestedCtrl">
<label>Primitive</label>
<input type="text" ng-model="name">
<label>Primitive with explicit $parent reference</label>
<input type="text" ng-model="$parent.name">
<label>Object</label>
<input type="text" ng-model="user.name">
</div>
</div>
</body>
This is all from that link I provided.

Categories