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

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.

Related

Cannot get value of ng-model through $scope

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>

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.

Passing Values in Angular JS

I'm a newbie to Angular JS. I've created a form in my index.html page, when I fill the details in the form and press submit, it should redirect to details.html page. Where I can able to show the details filled on the form.
HTML
<html>
<script src="angular.min.js"> </script>
<script src="script.js"> </script>
</head>
<body ng-app="FormApp">
<div class="forms" ng-controller="CustomerDetailsController">
<form novalidate>
First Name:<br>
<input type="text" ng-model="firstName" required/>
<br>
<br>
Last Name:<br>
<input type="text" ng-model="lastName">
<br>
<br>
Age:<br>
<input type="text" ng-model="lastName">
<br>
<br>
Email :<br>
<input type="email" ng-model="lastName">
<br>
<br>
Location<br>
<input type="text" ng-model="lastName">
<br>
<br>
<button ng-click="submit()">SUBMIT</button>
</form>
</div>
</body>
</html>
CONTROLLER
var FormApp = angular.module('FormApp', []);
FormApp.controller('CustomerDetailsController', ['$scope',function($scope) {
$scope.submit = function() {
}
}]);
What will be the best way to do this? Any help would appreciated, Thanks.
You can achieve this by adding angular routing to your application which need ngRoute dependency. Then you need to define one parent controller that can hold the partial views common data like here it is mainCtrl.
Apart from that you missed few things while you created a form, form should have its name attribute so that angular will create a scope variable of that form and internally manages form validity inside that scope variable like $valid, $error, etc. Then the same name should be given to each form element, if you don't declare the name attribute, then it won't consider it as form element.
HTML
<html ng-app="app">
<head>
<script type="text/javascript" src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script type="text/javascript" src="http://code.angularjs.org/1.2.13/angular-route.js"></script>
<script src="example.js"></script>
</head>
<body>
<div ng-controller="mainCtrl">
<div class="forms">
<ng-view></ng-view>
</div>
</div>
</body>
</html>
CODE
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/view1', {
templateUrl: 'view1.html',
controller: 'CustomerDetailsController'
})
.when('/view2', {
templateUrl: 'view2.html',
controller: 'form2Ctrl'
})
.otherwise({
redirectTo: '/view1'
});
});
app.controller('mainCtrl', function($scope) {
$scope.form = {};
});
app.controller('CustomerDetailsController', function($scope,$location) {
$scope.submit = function(){
if($scope.form1.$valid)
$location.path('/view2');
};
});
app.controller('form2Ctrl', function($scope,$location) {
//this controller contain the data which will you get from
});
Working Plunkr
Update
Clearing confusion of on what form2Ctrl will contain as per request by #user3440121.
The second view may contain a ajax call that will fetch the user information from server and display it on the view or it can be any show the list of employees, Its depend on the whats the requirement of your application.
Basically you should not store data on client side as i did stored the data in form object and accessing it on view2 directly as I can access parent scope variable. I shown this only for demonstration purpose. In actual implementation we will take $route parameter from the URL & the we will make an ajax call to server which give data back to you. Currently in plunkr we redirecting to view2 using $location.path('/view2'); that would change to $location.path('/edit/1') and you need to add route to your app.config like
Route
.when('/edit/:id', {
templateUrl: 'view2.html',
controller: 'form2Ctrl'
})
Controller
app.controller('form2Ctrl', function($scope,$route) {
//we can get id here from $route object
console.log($route.params.id); //here it will be `id` which `1` in the URL
//now you have id you can make ajax to server and get required data
});
Hope above information cleared all the doubts about the question. Thanks.
Your $scope.submit function has nothing inside it for routing.
It should be:
$scope.submit = function($scope) {
$scope.$apply(function() {
$location.path("*place your details page here*");
});
}
Note that you also need to inject $location to your controller, as follows:
FormApp.controller('CustomerDetailsController',
['$scope', '$location', function($scope, $location) ...
Try reading the following for more details:
https://docs.angularjs.org/api/ng/service/$location
Also have you tried checking your paths? (e.g. angular.min.js, script.js)

Generate Dynamic ng-model for form Control in angularJS

I have an Array in my controller. On the basis of that Array I'm generating Input fields On my page.
My AngularJs code
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.names = ['morpheus', 'neo', 'trinity'];
});
And on page I'm generating my input fields
<form name="myForm1" ng-controller="MainCtrl">
<div ng-repeat="gg in names">
<input type="text" ng-model="control[index]"/>
</div>
<input type="submit" value="submit"/>
</form>
Now it generating ng-model for each textbox are control[index]
but I want to generate ng-model for each textbox like
control[0]
control[1]
control[2]
Plunker
you have to use
<input type="text" ng-model="control[$index]"/>
and there is no scope variable called control so you need to define the scope variable also, as below
$scope.control = {};
here is the updated Plunker

Angular JS how to pass value from rootscope into ng-model?

I have object into rootscope and i would like to display some values in form inputs.
I tried following:
<input type="number" ng-model="$root.order.id" class="form-control" id="orderNumber" />
But this is not working.
How i should pass value into ng-model?
Thanks for any help.
No need of attach de $root to the variable, the flow of scope in angular is first search in the local scope for the variable, if not found search the property in $scope.parent, and the rootScope if the high level of parent if not match with any else, then search there.
http://plnkr.co/edit/3ENyPRwrFq5ssR2uLtQy
In this plnkr look the usage of the root scope
Controller:
app.controller('MainCtrl', ["$scope", "$rootScope", function($scope, $rootScope) {
$rootScope.varRoot = {
element: "Jesús"
};
}]
);
HTML:
<body ng-controller="MainCtrl">
<p>Hello {{varRoot.element}}!</p>
<input type="text" ng-model="varRoot.element">
</body>
Just use the name, ex:
$rootScope.order.id = 3;
<input type="number" ng-model="order.id" class="form-control" id="orderNumber" />

Categories