Angular js application shows Syntax Error - javascript

I am consuming wcf service into angular js application . I am trying to invoke multi request from angular js application to wcf service . But the problem is when i run the application i got following errors in google chrome console windows .
Uncaught SyntaxError: missing ) after argument list
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.5/$injector/modulerr?
Here is the script code .
///// <reference path="../angular.min.js" />
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
$scope.OperType = 1;
//1 Mean New Entry
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.Tittle = "";
$scope.First_Name = "";
$scope.Last_Name = "";
$scope.Gender = "";
$scope.DOB = "";
$scope.Mobile = "";
$scope.House_No = "";
$scope.Streent_Name = "";
$scope.Country = "";
$scope.Post_Code = "";
$scope.Occupation = "";
}
$scope.CeditCardApplication = function () {
var ApplicationDeatils = {
Tittle: $scope.Tittle,
First_Name: $scope.First_Name,
Last_Name: $scope.Last_Name,
Gender: $scope.Gender,
DOB: $scope.DOB,
Mobile: $scope.Mobile,
House_No: $scope.House_No,
Streent_Name: $scope.Streent_Name,
Country: $scope.Country,
Post_Code: $scope.Post_Code,
Occupation: $scope.Occupation
};
myService.ApplicationDeatilsCheck(ApplicationDeatils).then(function (pl) {
console.log(pl.data)
if (pl.data) {
$scope.msg = "User information is correct !"
myService.ApplicationCreditScoreCheck(ApplicationDeatils1).then(function (p2) {
console.log(p2.data)
if (p2.data) {
$scope.msg = "We can offer you £6000";
}
else {
$scope.msg = "Application failed !";
console.log("Some error Occured" + err);
}
}, function (err) {
$scope.msg = "Application failed!";
console.log("Some error Occured" + err);
});
};
}
}]);
app.service("myService", function ($http) {
this.ApplicationDeatilsCheck = function (ApplicationDeatils) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/CreateCurrentAccountCheck", JSON.stringify(ApplicationDeatils));
}
this.ApplicationCreditScoreCheck = function (ApplicationDeatils) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/cheekCreditScore", JSON.stringify(ApplicationDeatils));
}
})
Here is the HTML CODE ..
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="WebClientModule">
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/CreditCardApplicationScript/ApplicationCheck.js"></script>
</head>
<body >
<table id="tblContainer" data-ng-controller="Web_Client_Controller">
<tr>
<td></td>
</tr>
<tr>
<td>
<table style="border: solid 4px Red; padding: 2px;">
<tr>
<td></td>
<td>
<span>Tittle</span>
</td>
<td>
<input type="text" id="Tittle" data-ng-model="Tittle" required="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Fisrt Name</span>
</td>
<td>
<input type="text" id="first_name" required data-ng-model="First_Name" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Last Name</span>
</td>
<td>
<input type="text" id="last_name" data-ng-model="Last_Name" required="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Gender</span>
</td>
<td>
<input type="text" id="gender" required data-ng-model="Gender" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Date Of Brith</span>
</td>
<td>
<input type="text" id="dob" data-ng-model="DOB" required="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Moblie/Telephone No</span>
</td>
<td>
<input type="text" id="mobile" required data-ng-model="Mobile" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> House No/Door No</span>
</td>
<td>
<input type="text" id="house_no" required data-ng-model="House_No" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Streent Name</span>
</td>
<td>
<input type="text" id="streent_name" required data-ng-model="Streent_Name" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Country</span>
</td>
<td>
<input type="text" id="country" required data-ng-model="Country" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Post Code</span>
</td>
<td>
<input type="text" id="post_code" required data-ng-model="Post_Code" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span> Occupation</span>
</td>
<td>
<input type="text" id="occupation" required data-ng-model="Occupation" require="" />
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<input type="button" id="CeditCardApplication" value="CeditCardApplication" data-ng-click="CeditCardApplication()" />
</td>
</tr>
</table>
<div style="color: red;">{{msg}}</div>
</td>
</tr>
</table>
</body>
</html>
Here is the screen shot when i run the application ..

The error is correct, you're missing a ) character and a }. Here's the code formatted a little better for ease of reading:
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
$scope.OperType = 1;
//1 Mean New Entry
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.Tittle = "";
$scope.First_Name = "";
$scope.Last_Name = "";
$scope.Gender = "";
$scope.DOB = "";
$scope.Mobile = "";
$scope.House_No = "";
$scope.Streent_Name = "";
$scope.Country = "";
$scope.Post_Code = "";
$scope.Occupation = "";
}
$scope.CeditCardApplication = function () {
var ApplicationDeatils = {
Tittle: $scope.Tittle,
First_Name: $scope.First_Name,
Last_Name: $scope.Last_Name,
Gender: $scope.Gender,
DOB: $scope.DOB,
Mobile: $scope.Mobile,
House_No: $scope.House_No,
Streent_Name: $scope.Streent_Name,
Country: $scope.Country,
Post_Code: $scope.Post_Code,
Occupation: $scope.Occupation
};
myService.ApplicationDeatilsCheck(ApplicationDeatils).then(function (pl) {
console.log(pl.data)
if (pl.data) {
$scope.msg = "User information is correct !"
myService.ApplicationCreditScoreCheck(ApplicationDeatils1).then(function (p2) {
console.log(p2.data)
if (p2.data) {
$scope.msg = "We can offer you £6000";
} else {
$scope.msg = "Application failed !";
console.log("Some error Occured" + err);
}
}, function (err) {
$scope.msg = "Application failed!";
console.log("Some error Occured" + err);
});
};
}); // <-- missing )
} // <-- missing }
}]);
app.service("myService", function ($http) {
this.ApplicationDeatilsCheck = function (ApplicationDeatils) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/CreateCurrentAccountCheck", JSON.stringify(ApplicationDeatils));
}
this.ApplicationCreditScoreCheck = function (ApplicationDeatils) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/cheekCreditScore", JSON.stringify(ApplicationDeatils));
}
});
This is one of those times where indentation and code-readability is super important.

Related

SyntaxError: Unexpected token `<` -- AngularJS Application is not working

I am currently working Wcf service with MVC . I am trying to consume my wcf service by using AngularJS and MVC Framework.I am trying to do insert, update and delete using wcf with AngularJS and mvc . My wcf service is working nicely but when I run AngularJS Application in Google Chrome its does not display any data in website and i Can not do insert , update and delete operation. I launch the developer tools and it is showing following errors..
d.sitespeeds.com/:2 Uncaught SyntaxError: Unexpected token <
angular.js:33671 WARNING: Tried to load angular more than once.
angular.js:4957 Uncaught Error: [$injector:modulerr] Failed to instantiate module RESTClientModule due to:
Error: [$injector:nomod] Module 'RESTClientModule' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.6.5/$injector/nomod?p0=RESTClientModule
at http://localhost:50349/Scripts/angular.js:116:12
at http://localhost:50349/Scripts/angular.js:2297:17
at ensure (http://localhost:50349/Scripts/angular.js:2218:38)
at module (http://localhost:50349/Scripts/angular.js:2295:14)
at http://localhost:50349/Scripts/angular.js:4933:22
at forEach (http://localhost:50349/Scripts/angular.js:410:20)
at loadModules (http://localhost:50349/Scripts/angular.js:4917:5)
at createInjector (http://localhost:50349/Scripts/angular.js:4839:19)
at doBootstrap (http://localhost:50349/Scripts/angular.js:1949:20)
at bootstrap (http://localhost:50349/Scripts/angular.js:1970:12)
at http://localhost:50349/Scripts/angular.js:116:12
at http://localhost:50349/Scripts/angular.js:2297:17
at ensure (http://localhost:50349/Scripts/angular.js:2218:38)
at module (http://localhost:50349/Scripts/angular.js:2295:14)
at http://localhost:50349/Scripts/angular.js:4933:22
at forEach (http://localhost:50349/Scripts/angular.js:410:20)
at loadModules (http://localhost:50349/Scripts/angular.js:4917:5)
at createInjector (http://localhost:50349/Scripts/angular.js:4839:19)
at doBootstrap (http://localhost:50349/Scripts/angular.js:1949:20)
at bootstrap (http://localhost:50349/Scripts/angular.js:1970:12)
http://errors.angularjs.org/1.6.5/$injector/modulerr?
at http://localhost:50349/Scripts/angular.js:116:12
at http://localhost:50349/Scripts/angular.js:4957:15
at forEach (http://localhost:50349/Scripts/angular.js:410:20)
at loadModules (http://localhost:50349/Scripts/angular.js:4917:5)
at createInjector (http://localhost:50349/Scripts/angular.js:4839:19)
at doBootstrap (http://localhost:50349/Scripts/angular.js:1949:20)
at bootstrap (http://localhost:50349/Scripts/angular.js:1970:12)
at angularInit (http://localhost:50349/Scripts/angular.js:1855:5)
at http://localhost:50349/Scripts/angular.js:33826:5
at HTMLDocument.trigger (http://localhost:50349/Scripts/angular.js:3468:5)
I also added the required AngularJS JavaScript Packages.Here is my AngularJS code for insert, update and delete operation . The wcf service is available on localhost under the pot number 50028. The name of the service is student service. The name of module is RESTClientModule and its registered with the controller.
/// <reference path="../angular.min.js" />
var app;
(function () {
app = angular.module("RESTClientModule", []);
app.controller("CRUD_AngularJs_RESTController", function ($scope, CRUD_AngularJs_RESTService) {
$scope.OperType = 1;
//1 Mean New Entry
GetAllRecords();
//To Get All Records
function GetAllRecords() {
var promiseGet = CRUD_AngularJs_RESTService.getAllStudent();
promiseGet.then(function (pl) { $scope.Students = pl.data },
function (errorPl) {
$log.error('Some Error in Getting Records.', errorPl);
});
}
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.StudentID = "";
$scope.Name = "";
$scope.Email = "";
$scope.Class = "";
$scope.EnrollYear = "";
$scope.City = "";
$scope.Country = "";
}
//To Create new record and Edit an existing Record.
$scope.save = function () {
var Student = {
Name: $scope.Name,
Email: $scope.Email,
Class: $scope.Class,
EnrollYear: $scope.EnrollYear,
City: $scope.City,
Country: $scope.Country
};
if ($scope.OperType === 1) {
var promisePost = CRUD_AngularJs_RESTService.post(Student);
promisePost.then(function (pl) {
$scope.StudentID = pl.data.StudentID;
GetAllRecords();
ClearModels();
}, function (err) {
console.log("Some error Occured" + err);
});
} else {
//Edit the record
debugger;
Student.StudentID = $scope.StudentID;
var promisePut = CRUD_AngularJs_RESTService.put($scope.StudentID, Student);
promisePut.then(function (pl) {
$scope.Message = "Student Updated Successfuly";
GetAllRecords();
ClearModels();
}, function (err) {
console.log("Some Error Occured." + err);
});
}
};
//To Get Student Detail on the Base of Student ID
$scope.get = function (Student) {
var promiseGetSingle = CRUD_AngularJs_RESTService.get(Student.StudentID);
promiseGetSingle.then(function (pl) {
var res = pl.data;
$scope.StudentID = res.StudentID;
$scope.Name = res.Name;
$scope.Email = res.Email;
$scope.Class = res.Class;
$scope.EnrollYear = res.EnrollYear;
$scope.City = res.City;
$scope.Country = res.Country;
$scope.OperType = 0;
},
function (errorPl) {
console.log('Some Error in Getting Details', errorPl);
});
}
//To Delete Record
$scope.delete = function (Student) {
var promiseDelete = CRUD_AngularJs_RESTService.delete(Student.StudentID);
promiseDelete.then(function (pl) {
$scope.Message = "Student Deleted Successfuly";
GetAllRecords();
ClearModels();
}, function (err) {
console.log("Some Error Occured." + err);
});
}
});
app.service("CRUD_AngularJs_RESTService", function ($http) {
//Create new record
this.post = function (Student) {
var request = $http({
method: "post",
url: "http://localhost:50028/StudentService.svc/AddNewStudent",
data: Student
});
return request;
}
//Update the Record
this.put = function (StudentID, Student) {
debugger;
var request = $http({
method: "put",
url: "http://localhost:50028/StudentService.svc/UpdateStudent",
data: Student
});
return request;
}
this.getAllStudent = function () {
return $http.get("http://localhost:50028/StudentService.svc/GetAllStudent");
};
//Get Single Records
this.get = function (StudentID) {
return $http.get("http://localhost:50028/StudentService.svc/GetStudentDetails/" + StudentID);
}
//Delete the Record
this.delete = function (StudentID) {
var request = $http({
method: "delete",
url: "http://localhost:50028/StudentService.svc/DeleteStudent/" + StudentID
});
return request;
}
});
});
Here is HTML Code....
<html data-ng-app="RESTClientModule">
#{
ViewBag.Title = "Manage Student Information using AngularJs, WCF REST & MVC4";
}
<body>
<table id="tblContainer" data-ng-controller="CRUD_AngularJs_RESTController">
<tr>
<td>
<table style="border: solid 2px Green; padding: 5px;">
<tr style="height: 30px; background-color: skyblue; color: maroon;">
<th></th>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Class</th>
<th>Year</th>
<th>City</th>
<th>Country</th>
<th></th>
<th></th>
</tr>
<tbody data-ng-repeat="stud in Students">
<tr>
<td></td>
<td><span>{{stud.StudentID}}</span></td>
<td><span>{{stud.Name}}</span></td>
<td><span>{{stud.Email}}</span></td>
<td><span>{{stud.Class}}</span></td>
<td><span>{{stud.EnrollYear}}</span></td>
<td><span>{{stud.City}}</span></td>
<td><span>{{stud.Country}}</span></td>
<td>
<input type="button" id="Edit" value="Edit" data-ng-click="get(stud)" />
</td>
<td>
<input type="button" id="Delete" value="Delete" data-ng-click="delete(stud)" />
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
<div style="color: red;">{{Message}}</div>
<table style="border: solid 4px Red; padding: 2px;">
<tr>
<td></td>
<td>
<span>Student ID</span>
</td>
<td>
<input type="text" id="StudentID" readonly="readonly" data-ng-model="StudentID" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Student Name</span>
</td>
<td>
<input type="text" id="sName" required data-ng-model="Name" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Email</span>
</td>
<td>
<input type="text" id="sEmail" required data-ng-model="Email" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Class</span>
</td>
<td>
<input type="text" id="sClass" required data-ng-model="Class" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Enrollement Year</span>
</td>
<td>
<input type="text" id="sEnrollYear" required data-ng-model="EnrollYear" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>City</span>
</td>
<td>
<input type="text" id="sCity" required data-ng-model="City" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Country</span>
</td>
<td>
<input type="text" id="sCountry" required data-ng-model="Country" />
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<input type="button" id="save" value="Save" data-ng-click="save()" />
<input type="button" id="Clear" value="Clear" data-ng-click="clear()" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
<script src="~/Scripts/MyScripts/Modules.js"></script>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular.min.js"></script>
Here is the Controller
public class StudentController : Controller
{
// GET: Student
public ActionResult Index()
{
return View();
}
}
There is BundleConfig
public class BundleConfig
{
// For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
Here is the screen shot When i run the Application ...
You didn't load your application correctly.
If <script src="~/Scripts/MyScripts/Modules.js"></script> contains your RESTClientModule then you should load your scripts like this inside the <head/> tag.
<head>
<title>#ViewBag.Title</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/MyScripts/Modules.js"></script>
</head>
Always load your modules after loading the angular library.
EDIT:
Here is how I resolved your issue.
Removed the call to _Layout.cshtml inside _ViewStart.cshtml
Added angular.min.js and Modules.js inside the <head></head> tag
Load angular.min.js before Modules.js
Modules.js
/// <reference path="../angular.min.js" />
var app;
(function () {
app = angular.module("RESTClientModule", []);
app.controller("CRUD_AngularJs_RESTController", function ($scope, CRUD_AngularJs_RESTService) {
$scope.OperType = 1;
//1 Mean New Entry
GetAllRecords();
//To Get All Records
function GetAllRecords() {
var promiseGet = CRUD_AngularJs_RESTService.getAllStudent();
promiseGet.then(function (pl) { $scope.Students = pl.data },
function (errorPl) {
$log.error('Some Error in Getting Records.', errorPl);
});
}
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.StudentID = "";
$scope.Name = "";
$scope.Email = "";
$scope.Class = "";
$scope.EnrollYear = "";
$scope.City = "";
$scope.Country = "";
}
//To Create new record and Edit an existing Record.
$scope.save = function () {
var Student = {
Name: $scope.Name,
Email: $scope.Email,
Class: $scope.Class,
EnrollYear: $scope.EnrollYear,
City: $scope.City,
Country: $scope.Country
};
if ($scope.OperType === 1) {
var promisePost = CRUD_AngularJs_RESTService.post(Student);
promisePost.then(function (pl) {
$scope.StudentID = pl.data.StudentID;
GetAllRecords();
ClearModels();
}, function (err) {
console.log("Some error Occured" + err);
});
} else {
//Edit the record
debugger;
Student.StudentID = $scope.StudentID;
var promisePut = CRUD_AngularJs_RESTService.put($scope.StudentID, Student);
promisePut.then(function (pl) {
$scope.Message = "Student Updated Successfuly";
GetAllRecords();
ClearModels();
}, function (err) {
console.log("Some Error Occured." + err);
});
}
};
//To Get Student Detail on the Base of Student ID
$scope.get = function (Student) {
var promiseGetSingle = CRUD_AngularJs_RESTService.get(Student.StudentID);
promiseGetSingle.then(function (pl) {
var res = pl.data;
$scope.StudentID = res.StudentID;
$scope.Name = res.Name;
$scope.Email = res.Email;
$scope.Class = res.Class;
$scope.EnrollYear = res.EnrollYear;
$scope.City = res.City;
$scope.Country = res.Country;
$scope.OperType = 0;
},
function (errorPl) {
console.log('Some Error in Getting Details', errorPl);
});
}
//To Delete Record
$scope.delete = function (Student) {
var promiseDelete = CRUD_AngularJs_RESTService.delete(Student.StudentID);
promiseDelete.then(function (pl) {
$scope.Message = "Student Deleted Successfuly";
GetAllRecords();
ClearModels();
}, function (err) {
console.log("Some Error Occured." + err);
});
}
});
app.service("CRUD_AngularJs_RESTService", function ($http) {
//Create new record
this.post = function (Student) {
var request = $http({
method: "post",
url: "http://localhost:50028/StudentService.svc/AddNewStudent",
data: Student
});
return request;
}
//Update the Record
this.put = function (StudentID, Student) {
debugger;
var request = $http({
method: "put",
url: "http://localhost:50028/StudentService.svc/UpdateStudent",
data: Student
});
return request;
}
this.getAllStudent = function () {
return $http.get("http://localhost:50028/StudentService.svc/GetAllStudent");
};
//Get Single Records
this.get = function (StudentID) {
return $http.get("http://localhost:50028/StudentService.svc/GetStudentDetails/" + StudentID);
}
//Delete the Record
this.delete = function (StudentID) {
var request = $http({
method: "delete",
url: "http://localhost:50028/StudentService.svc/DeleteStudent/" + StudentID
});
return request;
}
});
})();
Index.cshtml / Main View
<html data-ng-app="RESTClientModule">
<head title="ASAS">
<title></title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/MyScripts/Modules.js"></script>
</head>
<body>
<table id="tblContainer" data-ng-controller="CRUD_AngularJs_RESTController">
<tr>
<td>
<table style="border: solid 2px Green; padding: 5px;">
<tr style="height: 30px; background-color: skyblue; color: maroon;">
<th></th>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Class</th>
<th>Year</th>
<th>City</th>
<th>Country</th>
<th></th>
<th></th>
</tr>
<tbody data-ng-repeat="stud in Students">
<tr>
<td></td>
<td><span>{{stud.StudentID}}</span></td>
<td><span>{{stud.Name}}</span></td>
<td><span>{{stud.Email}}</span></td>
<td><span>{{stud.Class}}</span></td>
<td><span>{{stud.EnrollYear}}</span></td>
<td><span>{{stud.City}}</span></td>
<td><span>{{stud.Country}}</span></td>
<td>
<input type="button" id="Edit" value="Edit" data-ng-click="get(stud)" />
</td>
<td>
<input type="button" id="Delete" value="Delete" data-ng-click="delete(stud)" />
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
<div style="color: red;">{{Message}}</div>
<table style="border: solid 4px Red; padding: 2px;">
<tr>
<td></td>
<td>
<span>Student ID</span>
</td>
<td>
<input type="text" id="StudentID" readonly="readonly" data-ng-model="StudentID" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Student Name</span>
</td>
<td>
<input type="text" id="sName" required data-ng-model="Name" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Email</span>
</td>
<td>
<input type="text" id="sEmail" required data-ng-model="Email" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Class</span>
</td>
<td>
<input type="text" id="sClass" required data-ng-model="Class" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Enrollement Year</span>
</td>
<td>
<input type="text" id="sEnrollYear" required data-ng-model="EnrollYear" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>City</span>
</td>
<td>
<input type="text" id="sCity" required data-ng-model="City" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Country</span>
</td>
<td>
<input type="text" id="sCountry" required data-ng-model="Country" />
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<input type="button" id="save" value="Save" data-ng-click="save()" />
<input type="button" id="Clear" value="Clear" data-ng-click="clear()" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
_ViewStart.cshtml
#{
Layout = null;//"~/Views/Shared/_Layout.cshtml";
}
Output:
P.S. Try to understand first the components of ASP.NET MVC and AngularJS independently before trying to merge the two.

Angularjs - how to update Dropdown depending on other Dropdown in Dynamic table?

var myAppRxCafe = angular.module('DescRxCafe', []);
myAppRxCafe.controller('RxCafeController', ['$scope', '$http', function($scope, $http) {
$scope.RxItemDetailArray = [];
$http.get("/URL ")
.then(function(response) {
var itemListArray = response.data.records;
for (var i = 0; i != response.data.records.length; i++) {
$scope.RxItemDetailArray.push({
'itemName': itemListArray[i].u_item_name,
'itemPrice': itemListArray[i].u_itemprice_decimal
});
console.log('Data from Server- ' + JSON.stringify(response.data.records));
}
});
$scope.RxCafeObj = [{
'rxCafeReqItem': '',
'rxCafeReqQty': 1,
'rxCafeReqTime': '',
'rxCafeReqOrderNotes': '',
'rxCafeReqPrice': 0,
'rxCafeReqTotalPrice': 0,
}];
$scope.addRow = function() {
$scope.rxCafeReqItem = '';
$scope.rxCafeReqQty = 1;
$scope.rxCafeReqTime = '';
$scope.rxCafeReqOrderNotes = '';
$scope.rxCafeReqPrice = 0;
$scope.rxCafeReqTotalPrice = 0;
$scope.RxCafeObj.push({
'rxCafeReqItem': $scope.rxCafeReqItem,
'rxCafeReqQty': $scope.rxCafeReqQty,
'rxCafeReqTime': $scope.rxCafeReqTime,
'rxCafeReqOrderNotes': $scope.rxCafeReqOrderNotes,
'rxCafeReqPrice': $scope.rxCafeReqPrice,
'rxCafeReqTotalPrice': $scope.rxCafeReqTotalPrice,
});
};
$scope.updatePrice = function(itemSelected) {
$scope.availablePrice = [];
angular.forEach($scope.RxItemDetailArray, function(value) {
if (value.itemName == itemSelected) {
$scope.availablePrice.push(value.itemPrice);
}
});
};
$scope.removeRow = function($index) {
if ($index != 0) {
$scope.RxCafeObj.splice($index, 1);
}
};
}]);
<div ng-app="DescRxCafe" ng-csp="no-unsafe-eval" id="divId2">
<div ng-controller="RxCafeController">
<table style="height: 28px;" width="430" class="table table-bordered" id="dataTable_RxCafeController">
<tbody>
<tr>
<th>Requested Item</th>
<th>Quantity</th>
<th>Time</th>
<th>Order Notes</th>
<th>Price</th>
<th>Total Price(Qty * price * 0.06)</th>
</tr>
<tr ng-repeat="company in RxCafeObj">
<td>
<select class="form-control input1" ng-model="rxItemName" name="rxCafeReqItem" id="selectedElectronicRec" ng-change="updatePrice(rxItemName)">
<option value='none_RxCafeController_input'>None</option>
<option ng-repeat="v in RxItemDetailArray | orderBy:'itemName':false" value="{{v.itemName}}">{{v.itemName}}</option>
</select>
</td>
<td>
<input type="number" class="form-control input1" id="RxCafeController_input" ng-model="rxQty" value="{{company.rxCafeReqQty}}" name="rxCafeReqQty" />
</td>
<td>
<input type="date" class="form-control input1" id="RxCafeController_input" name="rxCafeReqTime" />
</td>
<td>
<input type="text" class="form-control input1" id="RxCafeController_input" name="rxCafeReqOrderNotes" />
</td>
<td>
<select class="form-control input1" ng-model="rxPrice" name="rxCafeReqItemPrice" id="RxCafeController_input">
<option ng-repeat="v in availablePrice " value="{{v}}" ng-selected="{{v}}">{{v}}</option>
</select>
</td>
<td>
<input type="number" class="form-control input1" id="RxCafeController_input" ng-model="rxTotalPrice" value="{{rxPrice*rxQty*0.06}}" ng-disabled="true" name="rxCafeReqTotalPrice" />
</td>
<td>
<input type="button" value="Delete" ng-click="removeRow($index)" name="Delete" />
</td>
</tr>
</tbody>
</table>
<input type="submit" class="button" id="dataTable2_input" value="Add another line" ng-click="addRow('')" />
</div>
</div>
Can you check for loop used in your code,
$http.get("/URL ").then(function(response) {
//$scope.RxCafeLocationArray = response.data.records;
var itemListArray= response.data.records;
for(var i=0;i!=response.data.records.length;i++){
$scope.RxItemDetailArray.push({'itemName':itemListArray[i].u_item_name,'itemPrice':itemListArray[i].u_itemprice_decimal});
console.log('Data from Server- '+JSON.stringify(response.data.records));
}
condition in for loop seems confusing, it should be <=rather than !=

How do i iterate over array of json objects using ng-repeat in angular js?

i am trying to iterate over array of objects in angular js but i am getting error as cannot set property of undefined even though i had defined it.
Please find my code below :
var app = angular.module('myDemoApp', []);
app.service('MyTaskService', function($http) {
var services = {
userList: userList,
};
function userList(req) {
if (req == undefined)
req = {};
return $http({
url: "https://jsonplaceholder.typicode.com/posts",
method: "GET",
data: req
});
}
return services;
});
app.controller('MyTaskController', function($scope, MyTaskService) {
$scope.resp = {};
$scope.getPrjDetails = function() {
try {
var promise = MyTaskService.userList();
promise.then(function (sucResp) {
try {
$scope.resp = sucResp.data;
} catch (exception) {
console.log(exception);
return;
}
}
, function (errResp) {
console.log(errResp);
return;
});
} catch (exception) {
console.log(exception);
return;
}
}
});
Find my template :
<ul>
<li ng-repeat="myData in resp">{{myData.id}}</li>
</ul>
how can i iterate over all the json values and display in my textboxes in template or my list?
<div ng-app="myDemoApp">
<div ng-controller="MyTaskController">
<table tyle="float:right;">
<tr><h3>New Project Form</h3></tr>
<tr>
<td class='padding-to-controls'>Get Project Details</td>
<td class='padding-to-controls'>
<select ng-change="getPrjDetails()" ng-model="select_project" >
<option value=''>Select Project Details</option>
<option value='get-details'>Get Project Details</option>
</select>
</td>
</tr>
<tr>
<td class='padding-to-controls'>New Project Name <span>*</span></td>
<td class='padding-to-controls'> <input type = 'text' ng-model="project_name" ></td>
</tr>
<tr>
<td class='padding-to-controls'>Assign location to project <span>*</span></td>
<td class='padding-to-controls'> <input type = 'text' ng-model="assign_location" ></td>
</tr>
<tr>
<td class='padding-to-controls'>Area </td>
<td class='padding-to-controls'><input type = 'text' ng-model="area" ></td>
</tr>
<tr>
<td class='padding-to-controls'>City</td>
<td class='padding-to-controls'><input type = 'text' ng-model="city" ></td>
</tr>
<tr>
<td class='padding-to-controls'>State </td>
<td class='padding-to-controls'><input type = 'text' ng-model="state" ></td>
</tr>
<tr>
<td class='padding-to-controls'>Cluster</td>
<td class='padding-to-controls'><input type = 'text' ng-model="cluster" ></td>
</tr>
<tr>
<td class='padding-to-controls'>Region</td>
<td class='padding-to-controls'><input type = 'text' ng-model="region" ></td>
</tr>
<tr>
<td class='padding-to-controls'>Type <span>*</span> </td>
<td class='padding-to-controls'><input type = 'text' ng-model="type" ></td>
</tr>
<tr>
<td class='padding-to-controls'>Priority <span>*</span></td>
<td class='padding-to-controls'><input type = 'text' ng-model="priority" ></td>
</tr>
<tr>
<td class='padding-to-controls'>Name of approver<span>*</span></td>
<td class='padding-to-controls'><input type = 'text' ng-model="name_approver" ></td>
</tr>
<tr>
<td class='padding-to-controls'></td>
<td class='padding-to-controls'><button ng-click="getPrjDetails()">EDIT</button></td>
</tr>
</table>
</div>
</div>
please find link to my json i am trying to access :: https://jsonplaceholder.typicode.com/posts
When dom is first rendered, angular start searching for resp.data, which in your case is undefined and so angular will complain.
You don't need to pass $scope variables to any of the controller functions. They can access it directly.
In your whole code, you are never ever setting $scope.resp.
Your html context is way different from what you are trying to do. So I have modified it a bit. Try following code:
HTML:
<div ng-app="myDemoApp">
<div ng-controller="MyTaskController">
<h3>Feeds</h3>
<button ng-click="getPrjDetails()">Load</button>
<div ng-repeat="myData in resp.data">
<span> {{myData.id}}</span>
<input ng-model="myData.title" type="text" />
</div>
</div>
Angular
app.controller('MyTaskController', function($scope, MyTaskService) {
// Required
$scope.resp = {
data: []
}
$scope.getPrjDetails = function() {
try {
var promise = MyTaskService.userList();
promise.then(function(sucResp) {
try {
var resp = sucResp.data || [];
// You must update $scope.resp.data
$scope.resp.data = resp;
console.log($scope.resp.data);
} catch (exception) {
console.log(exception);
return;
}
}, function(errResp) {
console.log(errResp);
return;
});
} catch (exception) {
console.log(exception);
return;
}
}
})
fiddle working

Angular js model value changes are not reflected in ui

Values in the UI doesn't change even after executing the code in controller.
It displays the initial values with out a problem.
I've tried calling $scope.$apply() at the end of each function (submit and transfer) but it didn't work(it only gave an error with the $http.post()). What am i missing here?
app.controller('RegisterController', ['$scope','$http', function($scope,$http) {
$scope.user = {
email: 'admin#blah.com',
password1: '1qaz2wsx',
password2:'1qaz2wsx',
password:'1qaz2wsx',
username:'Admin',
profile_picture:'',
dobDay:'12',
dobMonth:'12',
dobYear:'1993',
date_of_birth:'',
stateMessage:'',
messageColor:'white',
};
var transfer = function(){
$http.post('http://localhost/cw/index.php/rest/resource/user/action/create',$scope.user).then(function successCallback(response) {
if(response.data.status!=null){
if(response.data.status=='success'){
$scope.user.stateMessage = 'success';
$scope.user.messageColor = "green";
}
else if(response.data.status=='failure'){
$scope.user.stateMessage = response.data.message;
$scope.user.messageColor = "red";
}
}
},function errorCallback(response) {
$scope.user.stateMessage = "Error occured.";
$scope.user.messageColor = "red";
});
};
$scope.submit = function(){
$scope.user.stateMessage="";
$scope.user.messageColor="white";
var proceed = true;
if(!validateFields()){
$scope.user.stateMessage = "All fields must be filled!";
$scope.user.messageColor = "red";
proceed = false;
}
if(validateDate($scope.user.dobDay,$scope.user.dobMonth,$scope.user.dobYear)){
$scope.user.date_of_birth= $scope.user.dobYear+"-"+$scope.user.dobMonth+"-"+$scope.user.dobDay;
}else {
proceed = false;
$scope.user.stateMessage = "Date is invalid!";
$scope.user.messageColor = "red";
}
if($scope.user.password1!=$scope.user.password2){
proceed = false;
$scope.user.stateMessage = "Passwords don't match!";
$scope.user.messageColor = "red";
}else $scope.user.password = $scope.user.password1;
if(proceed){
var file = document.getElementById('filePicker').files[0];
reader = new FileReader();
reader.onloadend = function(e) {
$scope.user.profile_picture = JSON.stringify(e.target.result);
$scope.$apply();
console.log($scope.user.profile_picture);
transfer();
}
reader.readAsDataURL(file);
}
function validateFields(){
/*some form validation*/
return true;
}
function validateDate(day,month,year){
/*some date validation*/
return true;
}
}
}]);
HTML code
<div ng-controller="RegisterController">
<span style="background-color:{{user.messageColor}}"><h4>{{user.stateMessage}}</h4></span>
</div>
<table style="text-align: left" ng-controller="RegisterController">
<tr>
<td>
Username
</td>
<td>
<input type="text" ng-bind="user.username" ng-model="user.username">
</td> <td> </td><td> </td>
</tr>
<tr>
<td>
Email
</td>
<td>
<input type="email" ng-bind="user.email" ng-model="user.email">
</td> <td> </td><td> </td>
</tr>
<tr>
<td>
Password
</td>
<td>
<input type="password" ng-bind="user.password1" ng-model="user.password1">
</td> <td> </td><td> </td>
</tr>
<tr>
<td>
Retype password
</td>
<td>
<input type="password" ng-bind="user.password2" ng-model="user.password2">
</td> <td> </td><td> </td>
</tr>
<tr>
<td>
Date of Birth
</td>
<td>
<input type="text" ng-bind="user.dobDay" ng-model="user.dobDay" value="DD" size="2" maxlength="2">
<input type="text" ng-bind="user.dobMonth" ng-model="user.dobMonth" value="MM" size="2" maxlength="2">
<input type="text" ng-bind="user.dobYear" ng-model="user.dobYear" value="YYYY" size="4" maxlength="4">
</td>
</tr>
<tr>
<td>
Profile picture
</td>
<td>
<input id="filePicker" type="file" ng-bind="user.profile_picture" ng-model="user.profile_picture" accept="image/*">
</td>
</tr>
<tr>
<td></td>
<td style="float:left">
<button ng-click="submit()">Submit</button>
</td>
</tr>
</table>
It seems like i cannot use the same controller in 2 instances.
Moving the status div in to the table assigned with the controller worked for me. There are ways to share data between controllers by using a service but i won't go there since this is only for a coursework.
AngularJS: share the data of the same controller in two different, not nested parts of the page

Call method from another ng-app in angular js

I have 2 ng-app block on same page. One for listing items, and the other one is for insert. I want to call listing function after I have finished insert.
I have tried something but I couldn't succeeded in.
I found some documents about calling functions on same ng-app but i need to call a function from another ng-app.
Here is my code, please help.
<body>
<div id="UserControllerDiv" ng-app="UserTableApp" ng-controller="UsersController" class="form-group">
<br /><br />
<p>Search : <input type="text" ng-model="search" /></p>
<table class="table table-hover">
<thead>
<tr>
<th>First Name</th>
<th>Middle Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="u in users | filter:search">
<td>{{ u.FirstName }} </td>
<td>{{ u.MiddleName }} </td>
</tr>
</tbody>
</table>
</div>
<br />
<div id="UserFormDiv" ng-app="UserFormApp" ng-controller="UserFormCtr" class="form-group">
<table class="form-group">
<tr>
<td>First Name</td>
<td> : </td>
<td><input type="text" ng-model="FirstName" class="" /> </td>
</tr>
<tr>
<td>Middle Name</td>
<td> : </td>
<td><input type="text" ng-model="MiddleName" /> </td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<button ng-click="submit()">Save</button>
</td>
</tr>
</table>
</div>
<script>
var userTableApp = angular.module("UserTableApp", []);
userTableApp.controller("UsersController",
function UsersController($scope, $http) {
$http.get("http://localhost:10160/UserService/Users")
.success(function (response) { $scope.users = response; });
});
var userFormApp = angular.module("UserFormApp", []);
userFormApp.controller("UserFormCtr",
function UserFormCtr($scope, $http) {
$scope.submit = function () {
var dataObj = {
FirstName: $scope.FirstName,
MiddleName: $scope.MiddleName
};
var res = $http.post("http://localhost:10160/UserService/AddUser", dataObj);
res.success(function (data, status, headers, config) {
/****** Here I want to call the UsersController function of UserTableApp ************/
/* I tried the code below but it did not work */
var scope = angular.element(document.getElementById("UserControllerDiv")).scope();
scope.$apply(function () { scope.UsersController($scope, $http); });
/*************************************************************************************/
});
res.error(function (data, status, headers, config) {
alert("failure message: " + JSON.stringify({ data: data }));
});
}
});
angular.bootstrap(document.getElementById("UserFormDiv"), ['UserFormApp']);
</script>
Thank you for all your help...
Here is how you call function from other controller app.
var scope = angular.element(document.getElementById("UserControllerDiv")).scope();
scope.yourfunctionName();
And the flow will go to the Function mentioned.
For assurance you can check presence of your method in scope object in console.
You were just about right.

Categories

Resources