Angularjs Cannot read property 'id' of undefined - javascript

I am new to angularjs, I'm trying to create a webapp that can access data from server and post the data to the server. But I'm facing issues, what I did in my application, I have created module,service,view and controller in separate files. I'm unable to access and post data to the server. Can anyone help me.
home.js(controller file)
var myapp = angular.module('demo').controller("homeController", function($scope,myService){
var userArray = {
Id:$scope.user.id,
Model:$scope.user.model,
Name:$scope.user.name,
Color:$scope.user.color,
Price: $scope.user.price
};
myService.async().then(function(d){
$scope.hello=d;
});
$scope.push = function(userArray){
myService.saveUser(userArray).then(function(response){
console.log("inserted");
});
}
});
userService.js(service file)
myapp.factory('myService',function($http){
var myService={
async : function(){
var promise= $http.get('http://jsonplaceholder.typicode.com/posts/1').then(function(response){
console.log(response);
return response;
});
return promise;
},
saveUser : function(user){
$http.post('http://jsonplaceholder.typicode.com/posts',user).success(
function(response,status,headers,config){
});
}
};
return myService;
});
restComponent.js(module file)
var myapp=angular
.module('demo',['ui.router'])
.config(function ($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home',{
url:'/home',
templateUrl:'Templates/home.html',
controller:'homeController'
})
.state('about', {
url:'/about',
templateUrl:'Templates/about.html',
controller:'aboutController'
})
.state('contact',{
url:'/contact',
templateUrl:'Templates/contact.html',
controller:'contactController'
});
});
home.html (view file)
<form ng-submit="mod.push();" ng-controller="homeController as mod">
Id:<br>
<input type="text" name="id" ng-model="mod.user.id"><br>
Model:<br>
<input type="text" name="model" ng-model="mod.user.model"><br>
Name:<br>
<input type="text" name="name" ng-model="mod.user.name"><br>
Color:<br>
<input type="text" name="color" ng-model="mod.user.color"><br>
Price:<br>
<input type="text" name="price" ng-model="mod.user.price"><br>
<br>
<input type="submit" >
</form>
<br>
<br>
<table>
<thead>
<th>UserId</th>
<th>Name</th>
<th>Country</th>
</thead>
<tbody>
<tr ng-repeat="employee in hello">
<td>{{employee.userId}}</td>
<td>{{employee.name}}</td>
<td>{{employee.country}}</td>
</tr>
</tbody>
</table>
index.html
<!doctype html>
<html lang="en" >
<head>
<meta charset="utf-8">
<title>RestApi</title>
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
<script src="bower_components/angular/angular.js"></script>
<script src="
https://cdnjs.cloudflare.com/ajax/libs/angular-ui- router/0.3.1/angular-ui-router.js
"></script>
<script src="rest-controller.component.js"></script>
<script src="Controllers/contact.js"></script>
<script src="Controllers/about.js"></script>
<script src="Controllers/home.js"></script>
<script src="Service/userService.js"></script>
</head>
<body ng-app="demo" >
<ol>
<li><a ui-sref="home">Home</a></li>
<li><a ui-sref="about">About</a></li>
<li><a ui-sref="contact">Contact</a></li>
</ol>
<div ui-view></div>
</body>
</html>

change that
you didnt declare your scope so its undefined that why better to declare it before using it
also removes that user array you did not need for that
var myapp = angular.module('demo').controller("homeController", function($scope,myService){
$scope.user = {}; // here you declare the user obkect
$scope.push = function(user){
myService.saveUser(user).then(function(response){
console.log("inserted");
});
}
})
and home html
you wanted to use scope but you used controller var
the view know the scope and all his objects so just write the var fun name and it will go to it directly
or you can do the same with controller by using this instead of scope and mod like you did
here you should send the user or you can do it in controller by sending the $scope.user
<form ng-submit="push(user);">
Id:<br>
<input type="text" name="id" ng-model="user.id"><br>
Model:<br>
<input type="text" name="model" ng-model="user.model"><br>
Name:<br>
<input type="text" name="name" ng-model="user.name"><br>
Color:<br>
<input type="text" name="color" ng-model="user.color"><br>
Price:<br>
<input type="text" name="price" ng-model="user.price"><br>
<br>
<input type="submit" >
</form>
and route
better to declare the controller on the view but you cant do them both so i chosed the view controller
var myapp=angular
.module('demo',['ui.router'])
.config(function ($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home',{
url:'/home',
templateUrl:'Templates/home.html'
})
.state('about', {
url:'/about',
templateUrl:'Templates/about.html'
})
.state('contact',{
url:'/contact',
templateUrl:'Templates/contact.html'
});
});
should work that way

Related

Angular -multi step form

How I can set val1 to $_POST variable ? Because in step 2 val1 is null.
I try to use $scope, $rootScope, angular.copy() and .val().
This is my html code:
<html ng-app="myApp"><body>
<form action="url.php" method="POST" ng-controller="FormController as vmForm">
<div ng-switch="vmForm.step">
<div class="stepone" ng-switch-when="one">
<label for="val1">Val1</label>
<input type="text" name="val1" ng-model="val1">
<button type="button" ng-click="vmForm.stepTwo()"></button>
</div>
<div class="steptwo" ng-switch-when="two">
<label for="val2">Val2</label>
<input type="text" name="val2" ng-model="val2">
<input type="submit" value="Submit">
</body>
JS
<script>
angular.module('myApp', ['ngAnimate'])
.controller('FormController', FormController);
function FormController($scope) {
var vm = this;
vm.step = "one";
vm.stepTwo = stepTwo;
function stepTwo() {
vm.step = "two";
}
}</script>
$_POST is a PHP variable that's accessible on the server. It contains the payload or request body that's sent in a HTTP POST request as an associative array. It cannot be set directly using Javascript / AngularJS.
What you can do is construct your request data and make a $http POST request to your form action endpoint. Here's a working example based on the code you posted: http://plnkr.co/edit/C1FGvoDrmzYEFMCwymIG?p=preview
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp">
<h1>Hello Plunker!</h1>
<form ng-submit="formSubmit()" ng-controller="FormController">
<p>Val1: {{val1}}</p>
<p>Val2: {{val2}}</p>
<div ng-switch="vm.step">
<div class="stepone" ng-switch-when="one">
<label for="val1">Val1</label>
<input type="text" name="val1" ng-model="$parent.val1">
<button type="button" ng-click="stepTwo()">Go to Step two</button>
</div>
<div class="steptwo" ng-switch-when="two">
<label for="val2">Val2</label>
<input type="text" name="val2" ng-model="$parent.val2">
<input type="submit" value="Submit">
</div>
</div>
</form>
</body>
</html>
script.js
var app = angular.module('myApp', []);
app.controller('FormController', ['$scope','$http',function ($scope,$http) {
$scope.vm = {
step : "one"
};
$scope.val1 = "";
$scope.val2 = "";
$scope.stepTwo = function () {
$scope.vm.step = "two";
}
$scope.formSubmit = function () {
console.log($scope.val1, $scope.val2);
var req = {
url : 'url.php',
method: 'POST',
data : {
val1 : $scope.val1,
val2 : $scope.val2
}
};
$http(req).then(function(response) {
console.log('success', response);
}, function(errorResponse){
console.log('error', errorResponse);
});
}
}]);
Just leave everything as is in your controller and tweak your HTML like this:
<form action="url.php" method="POST" ng-controller="FormController as vmForm">
<div ng-switch="vmForm.step">
<div class="stepone" ng-switch-when="one">
<label for="val1">Val1</label>
<input type="text" name="val1" ng-model="vmForm.val1">
<button type="button" ng-click="vmForm.stepTwo()">Goto Step 2</button>
</div>
<div class="steptwo" ng-switch-when="two">
<input type="hidden" name="val1" value="{{vmForm.val1}}">
<label for="val2">Val2</label>
<input type="text" name="val2" ng-model="val2">
<input type="submit" value="Submit">
</div>
</div>
</form>
The tweak to your code is simply raising the scope of "val1" to "vmForm.val1" so in Step 2 "vmForm.val1" can be assigned to a hidden input field for posting.
Here's the form fields being posted in the browsers debugger:
Here's a Plunker, http://plnkr.co/edit/3VaFMjZuH09A4dIr1afg?p=preview
Open your browsers debugger and view network traffic to see form fields being posted.

How to config view and contoller module in angular JS

how to link module controller and view in angulaaJS . i am trying to linking with below codes i am getting error please help me to find errors in a code .
controller code:
<!DOCTYPE html>
<html >
<head><title>Angular JS Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-view="" ng-app="myApp">
</div>
<script>
var app=angular.module('myApp',[]);
app.config(function ($routeProvider){
$routeProvider
.when('/view1.html',
{
controller:'myCtrl',
templateUrl:'Partials/view1.html'
})
.when('/view2',
{
controller:'myCtrl',
templateUrl:'Partials/view2.html'
})
.otherwise({redirectTo:'/view1'});
});
app.controller('myCtrl',function($scope){
$scope.customers=[
{name:'JohnSmith',city:'Phonenix'}
{name:'devsenny',city:'New York'}
{name:'benny',city:'san Francisco'}];
});
$scope.addCust=function(){
$scope.customers.push(
{
name:$scope.newcustomer.name,
city:$scope.newcustomer.city});
};
});
</script>
</body>
</html>
CODE FOR VIEW 1:
<div class="container">
<h2>View 1</h2>
Name:
<br/>
<input type="text" ng-model="filter.name"/>
<br/>
<ul>
<li ng-repeat="cust in customers">{{cust}}</li>
</ul>
<br/>
Customer Name:<br/>
<input type="text" ng-model="newcustomer.name">
<br/>
Customer city:<br/>
<input type="text" ng-model="newcustomer.city">
<br/>
<buttton ng-click="addCust()">AddCustomer</button>
</div>
CODE FOR VIEW 2:
<div class="container">
<h2>View 2</h2>
Name:
<br/>
<input type="text" ng-model="filter.name"/>
<br/>
<ul>
<li ng-repeat="cust in customers|filter:filter.name">{{cust}}</li>
</ul></div>
You just have to put your function into your controller ...
app.controller('myCtrl',function($scope){
$scope.customers=[
{name:'JohnSmith',city:'Phonenix'}
{name:'devsenny',city:'New York'}
{name:'benny',city:'san Francisco'}];
$scope.addCust=function(){
$scope.customers.push(
{
name:$scope.newcustomer.name,
city:$scope.newcustomer.city
});
};
});
on top of the #Steeve Pitis response, you need to run this in your web/app server not in your browser

Angular js: Iterate over list in view (ng-foreach)

I am getting json data in server response and return that to $scope.questions
I want to access this questions data in step1.html file.
app.js
(function () {
"use strict";
var app = angular.module("autoQuote",["ui.router","ngResource"]);
app.config(["$stateProvider","$urlRouterProvider", function($stateProvider,$urlRouterProvider){
$urlRouterProvider.otherwise("/");
$stateProvider
.state("step1", {
url : "/",
templateUrl : "easyquote/step1.html",
controller: "questionsCtrl",
})
.state("step2", {
url : "/step2",
templateUrl : "easyquote/step2.html",
controller: "questionsCtrl",
})
}]
);
}());
autoQuoteCtrl.js
(function () {
"use strict";
angular
.module("autoQuote")
.controller("questionsCtrl",["$scope","$http","$state",questionsCtrl]);
function questionsCtrl($scope,$http,$state) {
$http.get('rc1/getQuestions/' + $state.current.name)
.then(function(response) {
$scope.questions = response.data;
});
}
}());
step1.html
<div ng-controller="autoQuoteCtrl">
<form name="DTOstep1" ng-submit="onSubmit()">
<label>Email: </label><input type="text" name="email" id="email" />
<br><br>
<table ng-repeat="questions in que">
<tr>
<td>{{que.QuestionData._attributeName}}</td>
<td></td>
<tr>
</table>
<input type="submit" value="Save" />
</form>
</div>
Your usage of ng-repeat is the wrong way round. It should be like this:
<table ng-repeat="que in questions">
HTML
<table ng-repeat="questions in que">
<tr>
<td>{{questions._any_name}}</td>
<td></td>
<tr>
</table>

Argument 'myController' is not a function, got undefined

I'm trying to setup some controllers in my angular app but I'm not sure why I can't make them working, since I think I'm using similar approach as I've done before.
I declared app.js file:
'use strict';
var modules = [
'app.controllers',
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ui.router',
'LocalStorageModule',
'angular-loading-bar'
];
var app = angular.module('app', modules);
app.config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptorService');
})
app.factory('forgotPasswordService', ['$http', function ($http) {
var fac = {};
fac.forgotPassword = function (forgotPasswordData) {
return $http.post('/api/Account/ForgotPassword', forgotPasswordData)
};
return fac;
}])
app.factory('signUpService', ['$http', function ($http) {
var signUpServiceFactory = {};
signUpServiceFactory.saveRegistration = function (registration) {
return $http.post('/api/account/register', registration);
};
return signUpServiceFactory;
}]);
Then controllers.js file with this content:
angular.module('app.controllers', [])
.controller('signupController', [
'$scope', '$window', 'signUpService',
function($scope, $window, signUpService) {
$scope.init = function() {
$scope.isProcessing = false;
$scope.RegisterBtnText = "Register";
};
$scope.init();
$scope.IsLimitedCompany = null;
$scope.registration = {
Email: "",
Password: "",
ConfirmPassword: ""
};
$scope.signUp = function() {
$scope.isProcessing = true;
$scope.RegisterBtnText = "Please wait...";
signUpService.saveRegistration($scope.registration).then(function(response) {
alert("Registration Successfully Completed. Please sign in to Continue.");
$window.location.href = "login.html";
}, function() {
alert("Error occured. Please try again.");
$scope.isProcessing = false;
$scope.RegisterBtnText = "Register";
});
};
}
]);
And my html file:
<!DOCTYPE html>
<!--[if !IE]><!-->
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<script src="/Metronic/plugins/jquery.min.js" type="text/javascript"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-cookies.min.js"></script>
<script src="/Scripts/angular-resource.min.js"></script>
<script src="/Scripts/angular-sanitize.min.js"></script>
<script src="/Scripts/angular-route.min.js"></script>
<script src="/Scripts/angular-ui-router.min.js"></script>
<script src="/Angular/app.js"></script>
<script src="/Angular/controllers.js"></script>
<script src="/Scripts/angular-local-storage.min.js"></script>
<script src="/Scripts/loading-bar.min.js"></script>
<script src="/Angular/Services/authInterceptorService.js"></script>
</head>
<body class="login">
<div class="content" ng-app="app">
<!-- BEGIN REGISTRATION FORM -->
<div class="register-form" ng-controller="signupController">
<h3 class="font-green">Sign Up</h3>
<p class="hint"> Enter your account details below: </p>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Email</label>
<input class="form-control placeholder-no-fix" ng-model="registration.Email" type="text" autocomplete="off" placeholder="Email" name="username" />
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<input class="form-control placeholder-no-fix" ng-model="registration.Password" type="password" autocomplete="off" id="register_password" placeholder="Password" name="password" />
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Re-type Your Password</label>
<input class="form-control placeholder-no-fix" ng-model="registration.ConfirmPassword" type="password" autocomplete="off" placeholder="Re-type Your Password" name="rpassword" />
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Role</label>
<select name="role" ng-change="CheckRole()" ng-model="registration.Role" class="form-control">
<option value="">Role</option>
<option value="Borrower">Borrower</option>
<option value="Introducer">Introducer</option>
<option value="Investor">Investor</option>
<option value="Valuer">Valuer</option>
</select>
</div>
<div class="form-actions">
<button type="button" id="register-back-btn" class="btn green btn-outline">Back</button>
<button type="submit" id="register-submit-btn" class="btn btn-success uppercase pull-right" ng-click="signUp()" ng-disabled="isProcessing" value="{{RegisterBtnText}}">
Submit
</button>
</div>
</div>
<!-- END REGISTRATION FORM -->
</div>
</body>
</html>
Any idea what am I missing?
I'm getting this error:
Error: [ng:areq] Argument 'signupController' is not a function, got undefined
You have included JS file in wrong order.
Currently it is
<script src="/Angular/app.js"></script>
<script src="/Angular/controllers.js"></script>
Because of this your app.js not getting the defination of app.controllers.
Its should be like this one
<script src="/Angular/controllers.js"></script>
<script src="/Angular/app.js"></script>

Routing issues in Angular

I'm pretty new to Angular and I came across an issue I can't get around. I did see other people asking the same question, however their problem had to do with a missing ['ngRoute'] .I checked the code many times,but I might have missed something so I'm really hoping I can get some help on this one. Thanks in advance !
directories http://i.stack.imgur.com/zvaqU.png
firstpage.html :
<html ng-app="myApp">
<head>
</head>
<body>
<div ng-view></div>
<script
src="angular.min.js">
</script>
<script
src="angular-route.js">
</script>
<script
src="test.js">
</script>
</body>
</html>
test.js :
var app = angular.module('myApp',['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'SimpleController',
templateUrl: 'Partials/View1.html'
})
.when('/view2',
{
controller: 'SimpleController',
templateUrl: 'Partials/View2.html'
})
.otherwise({redirectTo:'/'});
});
var controllers = {};
controllers.SimpleController = function ($scope) {
$scope.djs=[{name:'Adam Beyer',city:'Sweden',djRank:1},
{name:'Joseph Capriati',city:'Napoli',djRank:4},
{name:'Nina Kraviz',city: 'Moscow',djRank:7},
{name:'Adam Petrov',city:'Sofia',djRank:100}];
$scope.addCustomer() = function () {
$scope.djs.push({name:$scope.newCustomer.name,
city:$scope.newCustomer.city});
};
};
app.controller(controllers);
View1.html :
<div class = "container">
<h2>View 1</h2>
Name:
<br/>
<input ng-model="filter.name" />
<br/>
<ul>
<li ng-repeat="dj in djs|filter:filter.name|orderBy:'djRank'"> {{dj.name}}
</li>
</ul>
<br/>
Customer Name: <br/>
<input type="text" ng-model="customer.name" />
<br/>
Customer City: <br/>
<input type="text" ng-model = "customer.city" />
<br/>
<button ng-click="addCustomer()">Add Customer</button>
</div>
View2.html :
<div class="container">
<h2>View 2</h2>
City:
<br/>
<input type = "text" ng-model="city" />
<br/>
<ul>
<li ng-repeat= "dj in djs |filter:city"</li>
</ul>
</div>
You made a typo in your controller. It should be
$scope.addCustomer = function () {
$scope.djs.push({name:$scope.newCustomer.name,
city:$scope.newCustomer.city});
};
not
$scope.addCustomer() = function () {
$scope.djs.push({name:$scope.newCustomer.name,
city:$scope.newCustomer.city});
};
Notice the parentheses right after addCustomer should not be there.

Categories

Resources