Call method from another ng-app in angular js - javascript

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.

Related

Knockout Observable not updating on Modal DOM/UI

Knockout observable value not updating on bootstrap Modal. In debug I can see that the value have been successfully added to observable. It just not updating/appearing on the modal DOM.
self.getSdsById = function (val) {
var ID = val.ID;
var operation = event.currentTarget.dataset['operation'];
$.ajax({
url: baseUrl + '/SdsView/getSdsByID',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: { 'ID': ID },
success: function (data) {
self.CopySdsDetail().RegistrationNo(data.Sds.RegistrationNo);
self.CopySdsDetail().MSDSIssueDate(data.Sds.MSDSIssueDate);
self.CopySdsDetail().Place(data.Sds.Place);
self.CopySdsDetail().Dept(data.Sds.Dept);
self.CopySdsDetail().Div(data.Sds.Div);
if (operation == 'COPY') {
$('#copyModalTitle').text('Copy & Add SDS to other Division');
$('#copyModal').modal();
}
}
}).fail(
function (xhr, textStatus, err) {
swal("Error", err, "error");
});
}
Modal :
<div class="modal fade" id="copyModal">
<div class="table-responsive" data-bind="with: CopySdsDetail">
<table class="table table-bordered table-sm">
<tr>
<td>Division: </td>
<td>Department: </td>
<td>Place: </td>
</tr>
<tr>
<td><input type="text" data-bind="value: Div"/></td>
<td><input type="text" data-bind="value: Dept"/></td>
<td><input type="text" data-bind="value: Place"/></td>
</tr>
<tr>
<td data-bind="text: RegistrationNo" colspan="2"></td>
<td data-bind="text: MSDSIssueDate"></td>
</tr>
</table>
</div>
</div>
Ko observable value in debug:
Any idea why?
in the short time I had to look at this, it generally looks ok, I got a very basic sample working with what you have provided. maybe it will help
var data = {
Dept: "Dicing",
Div: "DCG",
ID: 0,
MSDSIssueDate: "/Date(1602172800000)/",
Place: "Etching Process",
RegistrationNo: "DS-033"
}
function ViewModel() {
var self = this;
self.CopySdsDetail = ko.observable(new ModalViewModel());
self.clearData = function(){
self.CopySdsDetail(new ModalViewModel());
}
self.getData = function() {
self.CopySdsDetail(new ModalViewModel(data));
// self.CopySdsDetail().RegistrationNo(data.RegistrationNo);
// self.CopySdsDetail().MSDSIssueDate(data.MSDSIssueDate);
// self.CopySdsDetail().Place(data.Place);
// self.CopySdsDetail().Dept(data.Dept);
// self.CopySdsDetail().Div(data.Div);
}
}
function ModalViewModel(data){
var self = this;
data = data || {};
self.RegistrationNo = ko.observable(data.RegistrationNo || "");
self.Dept = ko.observable(data.Dept || "");
self.Div = ko.observable(data.Div || "");
self.ID = ko.observable(data.ID || "");
self.MSDSIssueDate = ko.observable(data.MSDSIssueDate || "");
self.Place = ko.observable(data.Place || "");
}
var vm = new ViewModel();
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div class="modal fade" id="copyModal">
<div class="table-responsive" data-bind="with: CopySdsDetail">
<table class="table table-bordered table-sm">
<tr>
<td>Division: </td>
<td>Department: </td>
<td>Place: </td>
</tr>
<tr>
<td><input type="text" data-bind="value: Div" /></td>
<td><input type="text" data-bind="value: Dept" /></td>
<td><input type="text" data-bind="value: Place" /></td>
</tr>
<tr>
<td data-bind="text: RegistrationNo" colspan="2"></td>
<td data-bind="text: MSDSIssueDate"></td>
</tr>
</table>
</div>
</div>
<button data-bind="click: getData">Get Data</button>
<button data-bind="click: clearData">Clear Data</button>

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.

How to remove extra added row for generated JSON on button click either using AngularJS or JavaScript?

I am performing few operations like Add and Remove for my two JSON files data.
My requirement is that I need to add respective json names and show them in the table and then need to generate json object for the added/selected json names on button click. It's working fine(that I can able to show my json names on UI table and can get/generate the json data object for my selected/added json names data after button click).
But, the issue is: after generating the json object or after clicking of Send button, I can see that one row is adding extra on my UI table after clicking of Send button, I don't need this added extra row for my UI table, I need only whatever I added the json names only those should be displayed in my table after clicking of Send button. It's happening for my two json tables.(I have two Send buttons individually, one for First JSON and other for Second JSON).
I am not sure what's the wrong here ? Please help me that to display the selected json names in table on button click, that shouldn't include one extra row adding either using AngularJS or JavaScript. Thank you in advance ! Created Plnkr.
html:
<div>
<p>First Table:</p>
<table>
<thead>
<tr>
<th>Name</th>
<th>Add</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(key, value) in myFirstJson.Testing">
<td>{{getKey(value)}}</td>
<td><button ng-click="addFirst(value)">Add</button></td>
</tr>
</tbody>
</table>
<br> <br>
<table border="1" class="table">
<thead>
<tr>
<th>Name</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(key, value) in firstJsonNames track by $index">
<td>{{getKey(value)}}</td>
<td><button ng-click="deleteFirst($index)">Delete</button></td>
</tr>
<tr ng-hide="firstJsonNames.length > 0">
<td colspan="3">
<p>No Names</p>
</td>
</tr>
</tbody>
</table>
<br>
<br>
<table>
<tbody>
<tr>
<td>First Dropdown:<select ng-model="firstJsonNames.firstdropdown">
<option value="Test1">Test1</option>
<option value="Test2">Test2</option>
<option value="Test3">Test3</option>
</select><br />
</td>
</tr>
<tr>
<td>First Input:<input type="text" maxlength="50" size="50"
ng-model="firstJsonNames.firstInput" /> <br /></td>
</tr>
</tbody>
</table>
<br>
<br>
<button ng-click="generateFirstJson()">Send</button>
<br>
<br><p>Second Table:</p>
<table>
<thead>
<tr>
<th>Name</th>
<th>Add</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(key, value) in mySecondJson.MyTest">
<td>{{value.Main.static.name}}</td>
<td><button ng-click="addSecond(value.Main.static.name)">Add</button></td>
</tr>
</tbody>
</table>
<br>
<br>
<table border="1" class="table">
<thead>
<tr>
<th>Name</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="name in secondJsonNames">
<td>{{name}}</td>
<td><button ng-click="deleteSecond(name)">Delete</button></td>
</tr>
<tr ng-hide="mySecondJson.MyTest.length">
<td colspan="3">
<p>No Names</p>
</td>
</tr>
</tbody>
</table>
<br>
<br>
<label>Enter Second Input Data:</label> <input
ng-model="secondJsonNames.SecondInput" placeholder="Input Text"><br>
<br>
<button ng-click="generateSecondJson()">Send</button>
<br>
<br>
</div>
app.js:
var app = angular.module('myApp', ['ui.router']);
app.controller('TestCtrl',function($scope, $http,$state,$stateParams,filterFilter,$rootScope) {
$rootScope.firstJsonNames = [];
$scope.secondJsonNames = [];
$scope.firstJsonNames.firstdropdown="Test1";
$scope.firstJsonNames.firstInput="1.5";
if($rootScope.myFirstJson == undefined)
{
$http.get('test.json').success(function(response) {
$rootScope.myFirstJson = response;
});
}
$scope.addFirst = function (name){
$rootScope.firstJsonNames.push(name);
console.log($rootScope.firstJsonNames);
};
$scope.deleteFirst = function (index){
$rootScope.firstJsonNames.splice(index,1);
};
$scope.getKey = function(item) {
return Object.keys(item)[0];
};
$scope.generateFirstJson = function(){
$rootScope.firstJsonNames.push({firstdropdown:$rootScope.firstJsonNames.firstdropdown, firstInput:$rootScope.firstJsonNames.firstInput});
console.log(angular.toJson($rootScope.firstJsonNames));
};
//second json
if($rootScope.mySecondJson == undefined)
{
$http.get('test1.json').success(function(response) {
$rootScope.mySecondJson = response;
});
}
$scope.addSecond = function (name){
$scope.secondJsonNames.push(name);
console.log($scope.secondJsonNames);
};
$scope.deleteSecond = function (name){
index = $scope.secondJsonNames.indexOf(name);
$scope.secondJsonNames.splice(index,1);
};
$scope.generateSecondJson = function(){
$scope.secondJsonNames.push({SecondInput:$scope.secondJsonNames.SecondInput});
console.log(angular.toJson($scope.secondJsonNames));
};
});
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'main.html',
controller: 'TestCtrl',
});
});
You are updating $rootScope.firstJsonNames and $scope.secondJsonNames, which are used in ng-repeat, So values are displaying in table. Use new variable for json creation.
For you are reference:
I have used
$scope.newjson2 = [];
$scope.newjson1 = [];
Plunker
http://plnkr.co/edit/r0VTaaT2rcfkiBNqyRmt?p=preview
JS:
var app = angular.module('myApp', ['ui.router']);
app.controller('TestCtrl',function($scope, $http,$state,$stateParams,filterFilter,$rootScope) {
$rootScope.firstJsonNames = [];
$scope.secondJsonNames = [];
$scope.firstJsonNames.firstdropdown="Test1";
$scope.firstJsonNames.firstInput="1.5";
$scope.newjson2 = [];
$scope.newjson1 = [];
if($rootScope.myFirstJson == undefined)
{
$http.get('test.json').success(function(response) {
$rootScope.myFirstJson = response;
});
}
$scope.addFirst = function (name){
$rootScope.firstJsonNames.push(name);
console.log($rootScope.firstJsonNames);
};
$scope.deleteFirst = function (index){
$rootScope.firstJsonNames.splice(index,1);
};
$scope.getKey = function(item) {
return Object.keys(item)[0];
};
$scope.generateFirstJson = function(){
$scope.newjson1 = angular.copy($rootScope.firstJsonNames);
$scope.newjson1.push({firstdropdown:$scope.firstJsonNames.firstdropdown, firstInput:$scope.firstJsonNames.firstInput});
console.log(angular.toJson( $scope.newjson1));
};
//second json
if($rootScope.mySecondJson == undefined)
{
$http.get('test1.json').success(function(response) {
$rootScope.mySecondJson = response;
});
}
$scope.addSecond = function (name){
$scope.secondJsonNames.push(name);
console.log($scope.secondJsonNames);
};
$scope.deleteSecond = function (name){
index = $scope.secondJsonNames.indexOf(name);
$scope.secondJsonNames.splice(index,1);
};
$scope.generateSecondJson = function(){
$scope.newjson2 = angular.copy($scope.secondJsonNames);
$scope.newjson2.push({SecondInput:$scope.secondJsonNames.SecondInput});
console.log(angular.toJson($scope.newjson2));
};
});
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'main.html',
controller: 'TestCtrl',
});
});

AngularJS search using filter not working

I am trying to search using angularjs filter method but its not working. I am not getting any errors in the console but still the search result is not showing up. Can someone help me on this.
This is my controller.js code:
.controller('SearchController',
[
'$scope',
'dataService',
'$location',
'$routeParams',
function ($scope, dataService, $location, $routeParams){
$scope.searchMovies = [ ];
$scope.searchCount = 0;
var getSearchResult = function (terms) {
dataService.getSearchResult(terms).then(
function (response) {
$scope.searchCount = response.rowCount + ' movies';
$scope.searchMovies = response.data;
$scope.showSuccessMessage = true;
$scope.successMessage = "All movie Success";
},
function (err){
$scope.status = 'Unable to load data ' + err;
}
); // end of getStudents().then
};
if ($routeParams && $routeParams.term) {
console.log($routeParams.term);
getSearchResult($routeParams.term);
}
}
]
);
This is the services.js code:
this.getSearchResult = function (terms) {
var defer = $q.defer(),
data = {
action: 'search',
term: terms
}
$http.get(urlBase, {params: data, cache: true}).
success(function(response){
defer.resolve({
data: response.ResultSet.Result,
rowCount: response.RowCount
});
}).
error(function(err){
defer.reject(err);
});
return defer.promise;
};
This is my app.js code:
. when('/search', {
templateUrl : 'js/partials/search.html',
controller : 'SearchController'
}).
This is the search.html code:
<div>
<label>Search: <input ng-model="searchMovie"></label><br><br><br><br>
</div>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="search in searchMovies | filter:searchMovie">
<td>
{{search.title}}
</td>
<td>
{{search.description}}
</td>
<td>
{{search.name}}
</td>
</tr>
</tbody>
</table>
The search data is being retrieved from the database. I have tested the SQL and it works fine. Just thee problem is in the angularjs server side. Thank you.
You need to give Alias for controller in your app.js file
.when('/search', {
templateUrl : 'js/partials/search.html',
controller : 'SearchController'
controllerAs: 'movies',
});
Now After This in your search.html file pass controllerAs
<div>
<label>Search: <input ng-model="searchMovie"></label><br><br><br><br>
</div>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="search in searchMovies | filter:searchMovie">
<td>
{{movies.search.title}}
</td>
<td>
{{movies.search.description}}
</td>
<td>
{{movies.search.name}}
</td>
</tr>
</tbody>

Get data-bind value of button in html table

How get data-bind value in ViewsModel from Button in html table when click ?
Please help me?
Views:
<table border="1">
<thead>
<tr>
<th>
Id
</th>
<th>
Naziv
</th>
</tr>
</thead>
<tbody data-bind="foreach: customers">
<tr>
<td data-bind="text: Id_dobavljaca">
</td>
<td data-bind="text: NazivDobavljaca">
</td>
<td>
<button data-bind="click: edit, value: Id_dobavljaca">
Edit</button>
<button >
Test</button>
</td>
</tr>
</tbody>
</table>
ViewModel:
define(function (require) {
var app = require('durandal/app'), system = require('durandal/system'),
ko = require('knockout');
return {
customers: ko.observableArray([]),
activate: prikazi
}
});
function prikazi() {
var system = require('durandal/system');
var that = this;
system.log('krenu po podatke');
$.ajax({
type: 'GET',
url: '/Durandal/VratiDobavljace',
dataType: "json",
success: function (data) {
that.customers(data);
},
error: function (jq, st, error) {
alert(error);
}
});
system.log('doneo podatke');
edit = function edit1(Id_dobavljaca) {
var system = require('durandal/system');
alert(Id_dobavljaca);
var router = require('plugins/router');
router.navigate('treci/' + 123456);
};
return that.customers
}
I want to pass value ( Id_dobavljaca )in ViewsModels when click button in html table..
Thanks alot!
Martin
In DurandalJS, the object that you return from your requirejs module that is your view model is the object bound to the view. The activate function will be called when DurandalJS composes your view and view model, you can read more here.
In your current implementation the observableArray customers is a property on your view model and can be bound to your view, which is great and I assume working.
However, from looking at your current implementation you have not exposed the edit function on your view model which means it cannot be bound to the UI and used.
I have refactored your view model:
define(function(require) {
var app = require('durandal/app'),
system = require('durandal/system'),
router = require('plugins/router'),
ko = require('knockout');
var customers = ko.observableArray([]);
return {
customers: customers,
edit: function(context) {
alert(context.Id_dobavljaca);
router.navigate('treci/' + context.Id_dobavljaca);
},
activate: function() {
system.log('krenu po podatke');
return $.ajax({
type: 'GET',
url: '/Durandal/VratiDobavljace',
dataType: "json"
})
.done(function(data) { customers(data); })
.fail(function(jq, st, error) { alert(error); })
.always(function() { system.log('doneo podatke'); });
}
}
});
This refactoring exposes the customers observableArray property and the edit function. The activate function also loads your data and returns the promise back to the DurandalJS composition life cycle.
Now, you will notice that the edit function takes an argument called context, this is a knockoutjs thing. When a function is bound to the click binding the first argument passed to the function is the binding context, you can read more here.
Using this refactored view model, in your markup you want to bind your edit button to the edit function on the $root context, which is your view model.
<td>
<button data-bind="click: $root.edit">Edit</button>
<button>Test</button>
</td>
Hopefully, the snippet below can demonstrate this explanation.
var example1 = {
customers: ko.observableArray([{
Id_dobavljaca: 123,
NazivDobavljaca: 'Martin',
edit: function(context) {
alert('Id_dobavljaca: ' + this.Id_dobavljaca);
alert('Id_dobavljaca: ' + context.Id_dobavljaca);
}
}, {
Id_dobavljaca: 321,
NazivDobavljaca: 'Anish',
edit: function(context) {
alert('Id_dobavljaca: ' + this.Id_dobavljaca);
alert('Id_dobavljaca: ' + context.Id_dobavljaca);
}
}, ])
}
ko.applyBindings(example1, $('#example1')[0]);
var example2 = {
customers: ko.observableArray([{
Id_dobavljaca: 123,
NazivDobavljaca: 'Martin'
}, {
Id_dobavljaca: 321,
NazivDobavljaca: 'Anish'
}, ]),
edit: function(context) {
alert('Id_dobavljaca: ' + context.Id_dobavljaca);
}
}
ko.applyBindings(example2, $('#example2')[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<p>Edit function is a property on each customer object<p>
<table id="example1" border="1">
<thead>
<tr>
<th>
Id
</th>
<th>
Naziv
</th>
</tr>
</thead>
<tbody data-bind="foreach: customers">
<tr>
<td data-bind="text: Id_dobavljaca">
</td>
<td data-bind="text: NazivDobavljaca">
</td>
<td>
<button data-bind="click: edit">
Edit</button>
<button>
Test</button>
</td>
</tr>
</tbody>
</table>
<br>
<br>
<br>
<p>Edit function is a property on the view model<p>
<table id="example2" border="1">
<thead>
<tr>
<th>
Id
</th>
<th>
Naziv
</th>
</tr>
</thead>
<tbody data-bind="foreach: customers">
<tr>
<td data-bind="text: Id_dobavljaca">
</td>
<td data-bind="text: NazivDobavljaca">
</td>
<td>
<button data-bind="click: $root.edit">
Edit</button>
<button>
Test</button>
</td>
</tr>
</tbody>
</table>
I hope this helps.

Categories

Resources