AngularJS: can't find registered controller - javascript

I am new to angular but have created a fairly simple app. I have looked through other, similar questions but I don't see any obvious spelling mistakes.
in my html file
<div ng-controller="OutcomeController" data-ng-init= "init()">
<div class="title">
<h1>Runs</h1>
<br/>
</div>
<table width="98%">
<tr>
<td>
<div class="searchPlace">
<form ng-submit="showCprRequest()" class= "search-form">
<input type="text" class="search-input" ng-model="idText"
placeholder="Search Id" autofocus>
<button type="submit" class="search-submit" >Search</button>
</form>
</div>
</td>
</tr>
</table>
In my outcomes.js file
function OutcomeController ($scope, $rootScope, $location ,$http, $log, $routeParams, diceService) {
$scope.init = function () {
// get id from url parameter (html head part)
$scope.id=$routeParams.id;
console.log('here');
// if id already entered on the page, get it from there
if ($scope.iIdText != null && $scope.idText != undefined && $scope.idText != "") {
$scope.showCprRequest();
}
else if ($scope.id == null || $scope.id == undefined) {
$scope.showDefaultCprRequest();
}
else {
$scope.iIdText = $scope.id;
$scope.showCprRequest();
}
$scope.showCprRequest = function () {
if ($scope.IdText.length == 0) {
console.log('or there');
return;
}
console.log('here');
var requestUrl = baseUrl+ "/cpr/" + $scope.id;
$http({method: "GET", url: requestUrl}).
success(function (data, status) {
$scope.diceRequestDisplays = data;
$scope.itemsPerPage = $scope.totalItems;
}
});
};
angular.module('outcome', []).controller('OutcomeController', OutcomeController);
NONE of the console.logs are getting hit, and the error I get is that OutcomeController is not registered. But I do so on the bottom line correct? Is there anything obvious I am missing?

Because you did not add ng-app and CDN for the angular router.
We can use CDN or we can install an angular route using npm install.
the console is printed properly you need to add $scope.showDefaultCprRequest() because there is no function related to that.
You can find angular all the CDN from here:
https://cdnjs.com/libraries/angular.js/1.4.0
HTML:
<!doctype html>
<html ng-app="App">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-route.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div ng-controller="OutcomeController" ng-init= "init()">
<div class="title">
<h1>Runs</h1>
<br/>
</div>
<table width="98%"><tr>
<td>
<div class="searchPlace">
<form ng-submit="showCprRequest()" class= "search-form">
<input type="text" class="search-input" ng-model="idText" placeholder="Search Id" autofocus>
<button type="submit" class="search-submit" >Search</button>
</form>
</div>
</td>
</tr></table>
</div>
</body>
</html>
js:
var app = angular.module('App',['ngRoute']);
app.controller('OutcomeController', ['$scope', '$rootScope', '$location' ,'$http', '$log', '$routeParams', function ($scope, $rootScope, $location ,$http, $log, $routeParams)
{
$scope.init = function () {
// get id from url parameter (html head part)
console.log('here');
$scope.id=$routeParams.id;
// if id already entered on the page, get it from there
if ($scope.iIdText != null && $scope.idText != undefined && $scope.idText != "") {
$scope.showCprRequest();
}
else if ($scope.id == null || $scope.id == undefined) {
$scope.showDefaultCprRequest();
}
else {
$scope.iIdText = $scope.id;
$scope.showCprRequest();
}
$scope.showCprRequest = function () {
if ($scope.IdText.length == 0) {
console.log('or there');
return;
}
console.log('here');
var requestUrl = baseUrl+ "/cpr/" + $scope.id;
$http({method: "GET", url: requestUrl}).
success(function (data, status) {
$scope.diceRequestDisplays = data;
$scope.itemsPerPage = $scope.totalItems;
})
};
};
}]);

Related

ngClass is not changing color based on variable value

I want to display green text message when value is true, and red text when value is false.
angular app:
at the top of the controller, I declare my variable and initiate it true:
$scope.IsColor = true;
if (response.data.indexOf("Panelists sucessfully added") !== -1) {
$scope.IsColor = true;
$scope.Messages = response.data;
angular.element("#msg").focus()
return true;
}
else {
$scope.IsColor = false;
$scope.Messages = response.data;
angular.element("#msg").focus()
return false;
}
In HTML:
<div id="msg" ng-repeat="msg in Messages" ng-style="IsColor && {'color':'green'} || {'color': 'red'}">{{msg}}</div>
No matter what response is, either positive or negative, the text always displays in red.
Does anyone have an idea what is wrong here?
Thank you,
Erasmo
UPDATE
More html
<body>
<div class="container pt-5 pb-5">
<div class="row">
<div class="col-md-8">
<div ng-app="MyApp" ng-controller="MyController">
<div>
<input type="button" value="Upload" id="btn-upload" ng-click="Upload()" />
</div>
#* Excel Contents Table *#
<table class="table mt-4 mb-5" id="tblPanelists" ng-show="IsVisible">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
<tbody ng-repeat="p in Panelists">
<tr>
<td>{{p.Name}}</td>
<td>{{p.Email}}</td>
</tr>
</tbody>
</table>
<div id="msg" ng-repeat="msg in Messages" ng-style="IsColor && {'color':'green'} || {'color': 'red'}">{{msg}}</div>
<div class=" mt-3">
<button type="submit" class="btn btn-admin-blue" id="btn-add-panelists" ng-click="AddPanelists()"
ng-disabled="disableSubmit">
Submit
</button>
</div>
</div>
</div>
</div>
</div>
</body>
and the angularjs controller-function Add Panelists
The $scope.IsColor boolean is delcare outside the function AddPanelists, within the controller, and used inside the AddPanelists function
AddPanelists function:
$scope.AddPanelists = function () {
$scope.arr = new Array;
angular.forEach($scope.Panelists, function (item) {
var b = {
name: item.Name.trim(),
email: item.Email.trim()
};
$scope.arr.push(b);
});
if ($scope.webinarId !== '') {
if ($scope.arr.length > 0) {
var data = JSON.stringify({ 'panelists': $scope.arr, 'webId': $scope.webinarId.split(' ').join('') });
//Call the services
$http.post('/meetings/panelists/home/createpanelists', data)
.then(function (response) {
if (response.data.indexOf("Panelists sucessfully added") !== -1) {
$scope.IsColor = true;
$scope.Messages = response.data;
angular.element("#msg").focus()
return true;
}
else {
$scope.IsColor = false;
$scope.Messages = response.data;
angular.element("#msg").focus()
return false;
}
}, function (response) {
$scope.IsColor = false;
$scope.Messages = "Service unavailable. Please try again.";
angular.element("#msg").focus()
return false;
});
} else {
$scope.IsColor = false;
alert('Please make sure to select a list of Panelists.');
$scope.Messages = 'Please make sure to select a list of Panelists';
angular.element("#msg").focus()
return false;
}
}
else {
$scope.IsColor = false;
alert('Please make sure to enter an ID');
$scope.Messages = 'Please make sure to enter a Zoom Webinar ID';
angular.element("#msg").focus()
return false;
}
};
Not really an anwser, but there seems to be nothing really wrong as u see in the example.(Except that the $scope.Messages should always be an array instead of string. )
I've tried running your function with a 'mock' http-request, seems to be working fine. You need to check the response that is being returned from the http-request.
angular.module('MyApp', []).controller('MyController', function($scope, $q){
$scope.arr =[1,2,3];
$scope.webinarId = '1234';
$scope.IsColor = false;
function mock(isResolve){
return $q(function(resolve, reject){
setTimeout(function(){
if(isResolve){
resolve({data:['Panelists sucessfully added','message 1', 'message 2']});
}else{
reject({data: ['error 1', 'error 2']});
}
}, 1000);
});
}
$scope.AddPanelists = function () {
angular.forEach($scope.Panelists, function (item) {
var b = {
name: item.Name.trim(),
email: item.Email.trim()
};
$scope.arr.push(b);
});
if ($scope.webinarId !== '') {
if ($scope.arr.length > 0) {
// var data = JSON.stringify({ 'panelists': $scope.arr, 'webId': $scope.webinarId.split(' ').join('') });
//Call the services
// $http.post('/meetings/panelists/home/createpanelists', data)
mock(true).then(function (response) {
if (response.data.indexOf("Panelists sucessfully added") !== -1) {
$scope.IsColor = true;
$scope.Messages = response.data;
angular.element("#msg").focus()
return true;
}
else {
$scope.IsColor = false;
$scope.Messages = response.data;
angular.element("#msg").focus()
return false;
}
}, function (response) {
$scope.IsColor = false;
// this should be an array as $scope.Messages is used in ng-repeat
$scope.Messages = ["Service unavailable. Please try again."];
//angular.element("#msg").focus()
return false;
});
} else {
$scope.IsColor = false;
alert('Please make sure to select a list of Panelists.');
// this should be an array as $scope.Messages is used in ng-repeat
$scope.Messages = ['Please make sure to select a list of Panelists'];
// angular.element("#msg").focus()
return false;
}
}
else {
$scope.IsColor = false;
alert('Please make sure to enter an ID');
// this should be an array as $scope.Messages is used in ng-repeat
$scope.Messages = ['Please make sure to enter a Zoom Webinar ID'];
angular.element("#msg").focus()
return false;
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyController">
<div>
<input type="button" value="Upload" id="btn-upload" ng-click="Upload()" />
</div>
#* Excel Contents Table *#
<table class="table mt-4 mb-5" id="tblPanelists" ng-show="IsVisible">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
<tbody ng-repeat="p in Panelists">
<tr>
<td>{{p.Name}}</td>
<td>{{p.Email}}</td>
</tr>
</tbody>
</table>
<div id="msg" ng-repeat="msg in Messages" ng-style="IsColor && {'color':'green'} || {'color': 'red'}">{{msg}}</div>
<div class=" mt-3">
<button type="submit" class="btn btn-admin-blue" id="btn-add-panelists" ng-click="AddPanelists()"
ng-disabled="disableSubmit">
Submit
</button>
</div>
</div>

I want to take input from multiple text inputs and send them to my database, but only the last input sends

I have a mysql database/node backend, connected to an Angular frontend, that I am querying, specifically to send it the data from 3 simple text inputs in a form.
I believe my error is quite trivial for anyone with node/angular experience because I can successfully send my database input from one of the text inputs; however, when I try to detect and send data from all three inputs, it only sends the data from whichever input has its matching controller function as the last one (of the three) in my script.
Here is my html file and the script
var button = document.getElementById("clickButton");
const app = angular.module('app',[]);
app.service('appService', ['$http', function($http){
return {
'getSuggestion' : function(suggestion,callback){
$http.post('/getSuggestion', {
'suggestion': suggestion
}).success(function (response) {
callback(response);
})
.error(function (data, status, header, config) {
callback({
'error': true,
'message': "Something went wrong."
});
});
}
}
}]);
app.controller('app', function($scope,appService) {
//message send Function
$scope.$watch('messageInput', function (newValue, oldValue) {
//null check
if (newValue !== null) {
//wait for the button to be pressed
button.onclick = function() {
alert("USERNAME");
//call server query function
appService.getSuggestion(newValue, function (response) {
$scope.suggestionCollection = response.rows;
});
};
}
});
$scope.$watch('messageInput2', function (newValue, oldValue) {
//null check
if (newValue !== null) {
//wait for the button to be pressed
button.onclick = function() {
alert("PASSWORD");
//call server query function
appService.getSuggestion(newValue, function (response) {
$scope.suggestionCollection = response.rows;
});
};
}
});
$scope.$watch('messageInput3', function (newValue, oldValue) {
//null check
if (newValue !== null) {
//wait for the button to be pressed
button.onclick = function() {
alert("PASSWORD");
//call server query function
appService.getSuggestion(newValue, function (response) {
$scope.suggestionCollection = response.rows;
});
};
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="app" ng-controller="app">
<head>
<title>Node app</title>
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div class="formFields">
<form class="defaultForm" id="loginForm">
<input class="loginField" type="text" name="username" ng-model="messageInput" placeholder="username"> <br>
<input class="loginField" type="text" name="password" ng-model="messageInput2" placeholder="password"> <br>
<input class="loginField" type="text" name="username" ng-model="messageInput3" placeholder="pass conf"> <br>
<button id="clickButton" class="submitButton">submit</button>
</form>
</div>
<!--<script src="Scripts/login.js"></script>-->
<script src="js/angular.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
You have a $watch for each input, and you have a submit() for each input. This is why you send only the input that changed. If you want to send them all together you should hold one submit(), means one onClick() that will check all new values are not null and send them to the server, something like this:
$scope.$watch('allInput', function (newValues, oldValues) {
//null check
if (newValues.user !== null && newValues.pass !== null && newValues.pass2 !== null) {
//wait for the button to be pressed
button.onclick = function() {
alert("USERNAME");
alert("PASSWORD");
alert("PASSWORD CONF");
//call server query function
appService.getSuggestion(newValues, function (response) {
$scope.suggestionCollection = response.rows;
});
};
}
});
and the html:
<form class="defaultForm" id="loginForm">
<input class="loginField" type="text" name="username" ng-model="allInput.name" placeholder="username"> <br>
<input class="loginField" type="text" name="password" ng-model="allInput.pass" placeholder="password"> <br>
<input class="loginField" type="text" name="username" ng-model="allInput.pass2" placeholder="pass conf"> <br>
<button id="clickButton" class="submitButton">submit</button>
</form>
Of course getSuggestion() will change as well:
app.service('appService', ['$http', function($http){
return {
'getSuggestion' : function(data,callback){
$http.post('/getSuggestion', {
'name': data.name,
'pass': data.pass,
'pass2': data.pass2
}).success(function (response) {
callback(response);
})
.error(function (data, status, header, config) {
callback({
'error': true,
'message': "Something went wrong."
});
});
}
}
If I understand your question correctly, you want to watch for changes of values in all three input fields. If user types anything in any one of the three input fields, you want to send the values from all three input fields to your backend. And when user hits "Submit", you want to get values from all three input fields as well.
To solve this problem, you need two pieces:
set up a persistent click event handler on the button, as opposed to adding one only when some change happens. Note that in your code, you are updating this click handler each time one of the three input fields changes. This would cause the new input handler to overwrite the old one. That's why you only get the last touched value. I would recommend looking into the ng-click directive.
get inputs from all three form fields when any one of them is changed. This can be achieved through the ng-change directive. Or alternatively, you can put all three ngModels under one parent object and just $watch() that one parent object, as Hatzav Wolff suggests in his answer.
Here is how I would approach it:
var button = document.getElementById("clickButton");
const app = angular.module('app',[]);
app.service('appService', ['$http', function($http){
return {
'getSuggestion' : function(suggestion,callback){
$http.post('/getSuggestion', {
'suggestion': suggestion
}).success(function (response) {
callback(response);
})
.error(function (data, status, header, config) {
callback({
'error': true,
'message': "Something went wrong."
});
});
}
}
}]);
app.controller('app', function($scope,appService) {
$scope.handleChange= function() {
/* Do whatever you want with the input. They are all here */
console.log($scope.messageInput + ' ' + $scope.messageInput2 + ' ' + $scope.messageInput3);
}
$scope.handleSubmit= function() {
/* Do whatever you want with the input. They are all here */
console.log($scope.messageInput + ' ' + $scope.messageInput2 + ' ' + $scope.messageInput3);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="app" ng-controller="app">
<head>
<title>Node app</title>
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div class="formFields">
<form class="defaultForm" id="loginForm">
<input class="loginField" type="text" name="username" ng-model="messageInput" ng-change="handleChange()" placeholder="username"> <br>
<input class="loginField" type="text" name="password" ng-model="messageInput2"ng-change="handleChange()" placeholder="password"> <br>
<input class="loginField" type="text" name="username" ng-model="messageInput3" ng-change="handleChange()" placeholder="pass conf"> <br>
<button id="clickButton" ng-click="handleSubmit()" class="submitButton">submit</button>
</form>
</div>
<!--<script src="Scripts/login.js"></script>-->
<script src="js/angular.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>

Local storage not shown after refresh

I just can't get it working no matter what I do. Been sitting for hours and nothing. After submitting form I create local storage of values name, surname, email, so that I would be able to use them to fill up form so that user would not have to type them everytime.
submit() is in review.controller.js
(function () {
'use strict';
angular.module('app').controller('ReviewController', ReviewController);
ReviewController.$inject = ['$location', 'AuthenticationService', 'FlashService', 'UniversalService', '$scope', '$sce', '$rootScope','$route','$cookies','localStorageService'];
function ReviewController($location, AuthenticationService, FlashService, UniversalService, $scope, $sce, $rootScope,$route,$cookies,localStorageService) {
var vm = this;
vm.name = null;
vm.surname = null;
vm.Email = null;
vm.review = null;
vm.allgenres = [];
vm.submit = submit;
vm.allreviews = [];
$scope.localArray=[];
loadAllReviews();
submit();
$scope.templates = [{ name: 'man.main.view.html', url: 'main/main.view.html'}];
$scope.template = $scope.templates[0];
function loadAllReviews() {
UniversalService.GetAllReviews()
.then(function (review) {
vm.allreviews = review;
});
}
$scope.init = function () {debugger;
// $scope.$MainController.obtained_array = localStorage.getItem("storageKey");debugger;
$scope.storageKey = localStorage.getItem("storageKey");debugger;
};
$scope.storageKey = localStorage.getItem('storageKey');
/* $scope.$watch("storageKey", function() {debugger;
localStorage.setItem('storageKey', storageKey);
});*/
function submit() {
if($rootScope.name!=null) {
var JSONObject = {
"name":$rootScope.name,
"surname":$rootScope.surname,
"email":$rootScope.email,
"review":$rootScope.review
}
var temp={
"name":$rootScope.name,
"surname":$rootScope.surname,
"email":$rootScope.email
}
$scope.localArray.push(temp);
localStorageService.set("storageKey", $scope.localArray);
$scope.storageKey = localStorageService.get("storageKey");
// $rootScope.obtained_array = localStorageService.get("storageKey"); debugger;
console.log($scope.storageKey);debugger;
var Results = UniversalService.PostReview(JSON.stringify(JSONObject));
}
}
}
main.controller.js
'use strict';
var app= angular.module('app').controller('MainController', MainController);
MainController.$inject = ['$location', 'AuthenticationService', 'FlashService', 'UniversalService', '$scope', '$sce', '$rootScope','$log','PagerService','localStorageService','$mdDialog'];
function MainController($location, AuthenticationService, FlashService, UniversalService, $scope, $sce, $rootScope,$log,PagerService,localStorageService,$mdDialog) {
var vm = this;
vm.allreviews = [];
vm.allusers=[];
vm.allemails=[];
vm.all=[];
vm.avatars=[];
$scope.filteredAll = [];
$scope.all=[];
$scope.items=[];
$scope.pager = {};
$scope.setPage = setPage;
loadAllReviews();
loadAllEmails();
loadAllUsers();
loadAll();
loadAvatars();
initController();
setPage();
submit();
$scope.init = function () {
$scope.$parent.storageKey = localStorage.getItem("storageKey");debugger;
// $scope.obtained_array = localStorage.getItem("storageKey");
// console.log(obtained_array); debugger;
// $scope.storageKey = localStorage.getItem("storageKey");debugger;
};
function refresh() {
location.reload();debugger;
}
function loadAll() {
UniversalService.GetAll()
.then(function (a) {
$scope.all=a;
});
}
function loadAllUsers(callback) {
UniversalService.GetAll()
.then(function (response) {
$scope.users=response;
if (callback) {
callback(response);
}
});
}
function loadAllReviews() {
UniversalService.GetAllReviews()
.then(function (review) {
vm.allreviews = review;
});
}
function loadAllEmails() {
UniversalService.GetAllEmails()
.then(function (email) {
vm.allemails = email;
});
}
function setPage(page) {
loadAllUsers(function (response) {
if (response) {
if (page < 1 || page > $scope.pager.totalPages) {
return;
}
// get pager object from service
$scope.everything=response;
$scope.pager = PagerService.GetPager(response.length, page);
// get current page of items
$scope.items = response.slice($scope.pager.startIndex, $scope.pager.endIndex + 1);
}
});
}
function initController() {
$scope.setPage(1); // initialize to page 1
}
}
HTML file:
<div class="container padding-tb" id="Review">
<div ng-controller="ReviewController" ng-init="init()" ng-app id="Review">
<h2>Add review</h2>
<form name="form" ng-submit="vm.submit()" role="form">
<div >
<div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="text" ng-model="name" onchange="CallItems()" id="name" class="form-control" ng-model="vm.name" placeholder="Enter name here" required />
<span ng-show="form.name.$dirty && form.name.$error.required" class="help-block">Name is required</span>
</div>
</div>
<div>
<div class="form-group">
<label for="surname">Surname</label>
<input type="text" ng-model="surname" name="text" id="surname" class="form-control" ng-model="vm.surname" placeholder="Enter surname here" required/>
<span ng-show="form.surname.$dirty && form.surname.$error.required" class="help-block">Surname is required</span>
</div>
</div>
<div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" id="email" class="form-control" ng-model="vm.email" placeholder="Enter email here" required />
<span ng-show="form.email.$dirty && form.email.$error.required" class="help-block">Email is required</span>
</div>
</div>
<div>
<div class="form-group">
<label for="review">Review</label>
<input type="text" name="text" id="review" class="form-control" ng-model="vm.review" placeholder="Enter review here" required/>
<span ng-show="form.review.$dirty && form.review.$error.required" class="help-block">Review is required</span>
</div>
</div>
<div class="form-actions">
<button id="submit" type="submit" onclick="passInfo()" class="btn btn-primary">Submit</button>
<label style="display:none" id="label"><font color="white">Review succesfully created!
<a onclick="refresh()" href="../ang/#!/review">Add new review</a></label> or
View reviews!
</div>
</div>
</form>
<div>
<div ng-init="init()" class="slide-animate-container">
<div class="slide-animate" ng-include="main.view.html"></div>
</div>
</div>
</div>
Currently I add these values to button to test if values are added:
<button ng-disabled="localStorage.getItem('LS_wimmtkey') !== null"> {{obtained_array}}</button>
My main.view is inserted into the review.view (because form and reviews are on the same page, main is for the review listing and reviews are submitted form)
After submiting form all these values appear in the button, but after refreshing page none of them are shown anymore. I kind of understand that it is all because everything I do with local storage is inside submit() function, but I am not sure how to fix it
You can write a init function on second controller and set the local Storage value in a variable.So whenever you refresh the page, init function will be called and local storage value will be available for you to use it in View
see below line:
<button ng-disabled="localStorage.getItem('LS_wimmtkey') !== null"> {{obtained_array}}</button>
"obtained_array" belong to $rootScope, so $rootScope can't bind to the template(binding to $rootScope is not possible )
quick solution is: change the following line
in case of: MainController
$scope.obtained_array = localStorage.getItem("LS_wimmtkey");debugger;
in case of :ReviewController (you are setting in this ctrl "LS_wimmtkey")
$scope.$parent.obtained_array = localStorage.getItem("LS_wimmtkey");debugger;

Angular.js : on form submit action is not calling

I am trying to submit form on ng-submit event but form submit is not working.
$http,$state,dtoResource are injections
where dtoResource is factory which modify json data.
My code is as below
index.html
<!DOCTYPE html>
<html ng-app="autoQuote">
<head lang="en">
<meta charset="UTF-8">
<title>Angular Js DTO mgnt</title>
<!-- Style sheets -->
<link href="css/bootstrap.css" rel="stylesheet"/>
<link href="css/app.css" rel="stylesheet"/>
<!-- Library Scripts -->
<script src="js/jquery.js"></script>
<script src="js/angular.js"></script>
<script src="js/angular-ui-router.js"></script>
<!-- Application Script -->
<script src="app/app.js"></script>
<!-- Services -->
<script src="common/services/common.services.js"></script>
<script src="common/services/dtoResource.js"></script>
<!-- Controllers -->
<script src="app/ctrl/autoQuoteCtrl.js"></script>
<script src="app/ctrl/questionsCtrl.js"></script>
</head>
<body>
<ul>
<li>step 1
<li>step 2
</ul>
<div class="container">
<div ui-view=""></div>
</div>
</body>
</html>
step1.html
Email:
autoQuoteCtrl.js
(function () {
"use strict";
angular
.module("autoQuote")
.controller("autoQuoteCtrl", ["$http","$state","dtoResource",autoQuoteCtrl]);
function autoQuoteCtrl($http,$state,dtoResource) {
console.log('We are in form');
//self = this;
// if valid (check form validate true)
//console.log(dtoResource);
//call function from your service, and do something with it
dtoResource.rc1Step1DTO();
$http({
method : 'POST',
url : 'api.php',
data : { dtoObj: JSON.stringify(prepareAutoQuoteDTO.postAutoQuoteObj) }, // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
console.log(data);
if (!data.success) {
} else {
// if successful, bind success message to message
//$scope.message = data.message;
}
});
}
}());
dtoResource.js
(function () {
"use strict";
angular
.module("autoQuote")
.factory("dtoResource",
["$resource",
dtoResource]);
console.log('inside dtoResource');
function dtoResource(){
var prepareAutoQuoteDTO = {
postAutoQuoteObj : $.getAutoQuoteObject(),
initializeDriverObj: function(){
var driverLocObj = new Driver();
driverLocObj.PersonInfo = new PersonInfo();
driverLocObj.DriverLicense = new DriverLicense();
driverLocObj.Incident = new Incident();
return driverLocObj;
},
initializeAppInfo: function(){
var appInfoLocObj = new ApplicationInfo();
appInfoLocObj.Discount = new Discount();
return appInfoLocObj;
},
/*
* Initialize Vehicle object for autoQuoteDTO.js
*/
initializeVehicleObj: function(){
var vehicleLocObj = new Vehicle();
return vehicleLocObj;
},
/*
* store session info
*/
rc1Step1DTO: function(){
var emailId = $('#save_quote_email').val();
if (typeof emailId !== "undefined" && emailId && emailId != '' && emailId != 'Email Address'){
var email = new Email();
email.EmailTypeCd = 'PRIMARY';
email.EmailAddress = emailId;
this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo = this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo || new Contact();
this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails = [];
this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails.push(email);
}
}
};
return prepareAutoQuoteDTO;
}
}());
You have to add ng-app and ng-controller attributes to parent DOM elements.
And you can not invoke controller's instance in ng-submit :)
You should add special method in the controller, and call that one.
Something like this
<body ng-app>
<div ng-controller="autoQuoteCtrl">
<form ng-submit="onSubmit()">
...
</form>
</div>
</body>
And your controller something like this
angular
.module("autoQuote")
.controller("autoQuoteCtrl", ["$http","$state","dtoResource", function($http, $state, dtoResource) {
$scope.onSubmit = function() {
alert('hi, I was invoked on form submit');
};
}]);
PS: In this example I am using co called scope soup. It is simple to understand but it clusters the $scope with additional properties. It is not recommended approach now. Read about better approach here: http://www.technofattie.com/2014/03/21/five-guidelines-for-avoiding-scope-soup-in-angular.html
UPDATE
You have slight confusion in your code:
The route redirected to /, which was caught by questionsCtrl, but the relevant template had attribute ng-controller=autoQuoteCtrl. So which controller should be then used to respond to user action?? Not sure if that was intended :)
SOLUTION
The submit function should have been called like this
<form ng-submit="onSubmit()">
I forgot the () in the first example, sorry :)
html
<div ng-controller="formCtrl">
<form name="userForm" class="well form-search" >
<input type="text" ng-model="name" class="input-medium search-query" placeholder="Name" required >
<input type="email" ng-model="email" class="input-medium search-query" placeholder="Email" required >
<input type="text" ng-model="message" class="input-medium search-query" placeholder="Message" required >
<button type="submit" class="btn" ng-click="formsubmit(userForm.$valid)" ng-disabled="userForm.$invalid">Submit </button>
</form>
<pre ng-model="result">
{{result}}
</pre>
</div>
jsfile
var app = angular.module('formExample', []);
app.controller("formCtrl", ['$scope', '$http', function($scope, $http) {
$scope.url = 'submit.php';
$scope.formsubmit = function(isValid) {
if (isValid) {
$http.post($scope.url, {"name": $scope.name, "email": $scope.email, "message": $scope.message}).
success(function(data, status) {
console.log(data);
$scope.status = status;
$scope.data = data;
$scope.result = data; // Show result from server in our <pre></pre> element
})
}else{
alert('Form is not valid');
}
} }]);
click here

Angular pass input value to $rootScope variable

I have situation where I want to use $rootScope variable and update its value with the one entered in input field. I have sitauation code shortened to this DEMO:
HTML:
<div ng-controller="MyCtrl">
<input type="text" ng-model="foo" placeholder="Enter something" />
<input type="button" ng-click="doSomething()" value="Send" ng-disabled="foo == null" />
</div>
SCRIPT:
var myApp = angular.module('myApp', []);
function MyCtrl($scope, $rootScope) {
$rootScope.foo = null;
$scope.doSomething = function () {
alert("Hello, " + $rootScope.foo);
}
}
Any suggestions on how to pass input value to $rootScope variable would be great!
Although not recommended, Still if you want you can do it the following way
<div ng-controller="MyCtrl">
<input type="text" ng-model="foo" placeholder="Enter something" ng-change="onFooChange()" />
<input type="button" ng-click="doSomething()" value="Send" ng-disabled="foo == null" />
</div>
Script
var myApp = angular.module('myApp', []);
function MyCtrl($scope, $rootScope) {
$rootScope.foo = null;
$scope.onFooChange = function(){
$rootScope.foo = angular.copy($scope.foo);
}
$scope.doSomething = function () {
alert("Hello, " + $rootScope.foo);
}
}
When the value of text field is changed onFooChange function is called and the value is stored into $rootScope.
Here is an approach without using ng-change:
function MyCtrl($scope, $rootScope) {
$scope.foo=null;
$scope.doSomething = function () {
$rootScope.foo=$scope.foo;
alert("Hello, " + $rootScope.foo);
}
}

Categories

Resources