I am new in knockout. I want to make the list of students.
I have attached the list structure which returned from MVC as an image, Click here to view.
Js code:
var employeeListViewModel = {};
var employeeViewModel = {
id: "",
name: ko.observable("neenu"),
age: ko.observable(),
email: ko.observable(),
department: ko.observable(),
address: {
address1: ko.observable(),
city: ko.observable(),
State: ko.observable()
},
};
var employeePageViewModel = {
employee: employeeViewModel,
employees: employeeListViewModel
};
var dataSource = {
getemployees: function () {
getData("Employee/GetEmployees").then((data) => {
var result = ko.mapping.fromJS(data.data);
employeeListViewModel = result();
console.log(employeeListViewModel);
});
},
init: function () {
this.getemployees();
}
}.init();
ko.applyBindings(employeePageViewModel);
Html code:
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody data-bind="foreach: employees">
<tr>
<td data-bind="text: Name"></td>
<td data-bind="text: Id"></td>
</tr>
</tbody>
When I run this page ,It is neither displaying any error nor displaying data. Please help.
1) employeeListViewModel must be a ko.observableArray()
2) also when getting the result from your getData function just set the observableArray to the list:
employeeListViewModel(data.data); //assuming data.data is a [].
3) ko.mapping.fromJS(data.data); can be removed
Related
I am trying to make single ajax call to server and than to use response to call more AngularJS with same data. I use angular.min.js and ng-table.min.js to create html tables.
But it does not work for me.
Thank you for any help.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ng-table/0.8.3/ng-table.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ng-table/0.8.3/ng-table.min.css" />
<b>List of Orders 1:</b><br>
<div>
<div ng-controller="selectFilterController1">
<table ng-table="tableParams" id="datatable" class="table" show-filter="true" style="font-size: 11px;position: relative; width: 100%">
<tbody>
<tr ng-repeat="row in $data" ng-class="{'color-status-green': row.status === row.status}">
<td style="width:40px;white-space:nowrap;" title="Address from" data-title="'Address from'" filter="{board_address: 'text'}" sortable="'board_address'">{{ row.board_address }}</td>
<td style="width:40px;white-space:nowrap;" title="Address to" data-title="'Address to'" filter="{dest_address: 'text'}" sortable="'dest_address'">{{ row.dest_address }}</td>
<td style="width:40px;white-space:nowrap;" title="Last name" data-title="'Last name'" filter="{last_name: 'text'}" sortable="'last_name'">{{ row.last_name }}</td>
<td style="width:40px;white-space:nowrap;" title="Time" data-title="'Time'" filter="{created_at: 'text'}" sortable="'created_at'">{{ row.created_at }}</td>
</tr>
</tbody>
</table>
</div>
<br><b>List of Orders 2:</b><br>
<div ng-controller="selectFilterController2">
<table ng-table="tableParams" id="datatable" class="table" show-filter="true" style="font-size: 11px;position: relative; width: 100%">
<tbody>
<tr ng-repeat="row in $data" ng-class="{'color-status-green': row.status === row.status}">
<td style="width:40px;white-space:nowrap;" title="Address from" data-title="'Address from'" filter="{board_address: 'text'}" sortable="'board_address'">{{ row.board_address }}</td>
<td style="width:40px;white-space:nowrap;" title="Address to" data-title="'Address to'" filter="{dest_address: 'text'}" sortable="'dest_address'">{{ row.dest_address }}</td>
<td style="width:40px;white-space:nowrap;" title="Last name" data-title="'Last name'" filter="{last_name: 'text'}" sortable="'last_name'">{{ row.last_name }}</td>
<td style="width:40px;white-space:nowrap;" title="Time" data-title="'Time'" filter="{created_at: 'text'}" sortable="'created_at'">{{ row.created_at }}</td>
</tr>
</tbody>
</table>
</div>
When I call function ajaxCallOrders(), response is transfered to controllers, but
var app = angular.module('ngTableApp', ['ngTable']);
var datax;
app.controller('selectFilterController1', function($scope, $http, $filter, $q, NgTableParams) {
var datax;
$scope.arrayTemp = [];
module1 = function(response){
$scope.myData = angular.fromJson(response.data);
angular.forEach($scope.myData, function(element) {
$scope.arrayTemp.push(element);
});
datax=$scope.array = $scope.arrayTemp;
$scope.tableParams = new NgTableParams({page: 1, count: datax.length}, {data: datax, counts: [10, 15, 20, datax.length]});
}
})
app.controller('selectFilterController2', function($scope, $http, $filter, $q, NgTableParams) {
var datax;
$scope.arrayTemp = [];
module2 = function(response){
$scope.myData = angular.fromJson(response.data);
angular.forEach($scope.myData, function(element) {
$scope.arrayTemp.push(element);
});
datax=$scope.array = $scope.arrayTemp;
$scope.tableParams = new NgTableParams({page: 1, count: datax.length}, {data: datax, counts: [10, 15, 20, datax.length]});
}
})
ajaxCallOrders = (function(){
var orderListData = {"token": authToken, "limit": "50"};
$.ajax({
type: 'POST',
url: 'orders.php',
data: JSON.stringify(orderListData),
contentType: 'application/x-www-form-urlencoded',
dataType: 'text',
processData: false,
success: function( data, textStatus, jQxhr ){
var response = data;
module1(response);
module2(response);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
});
To contain methods and data that are injectable to multiple controllers, create an AngularJS service.
app.service("orders", function($http) {
var orderListData = {"token": authToken, "limit": "50"};
var config = { params: orderListData };
var ordersPromise = $http.get("orders.php",config);
this.getPromise = function() {
return ordersPromise;
});
};
Usage:
app.controller('selectFilterController2', function(orders, NgTableParams) {
orders.getPromise().then(function(response){
$scope.array = response.data;
var xLength = $scope.array.length;
$scope.tableParams = new NgTableParams(
{page: 1, count: xLength},
{data: datax, counts: [10, 15, 20, xLength]}
);
}
})
The service uses the $http service to execute an XHR GET request and store a promise. The orders service can be injected into multiple controllers or other custom services. The getPromise method returns a promise which contains the response from the GET request.
For more information, see
AngularJS Developer Guide - Creating Services
I'm trying to search user by their email id. This partially works. If I search users for the first time by entering a email and clicking search button, it works. But then if I search of another user, its searches filters automatically without pressing the search button.
I should be able to search user only after I click the search button. Thanks in advance
var myApp = angular.module("myApp", []);
myApp.controller("myController", function($scope) {
console.log("in controller...");
$scope.newUser = {};
$scope.info = "";
// Users array list
if (localStorage.getItem("users") === null) {
$scope.users = [{
email: "Vai#yahoo.com",
password: "Sha123",
firstName: "Vai",
lastName: "LSha",
contact: "123-223-8989",
role: "Super-Admin",
company: ""
},
{
email: "John#yahoo.com",
password: "John123",
firstName: "John",
lastName: "Doe",
contact: "281-283-2480",
role: "Supplier-Admin",
company: "Apple"
},
{
email: "Rick#yahoo.com",
password: "Rick123",
firstName: "Rick",
lastName: "Fraiser",
contact: "987-283-2489",
role: "Supplier-User",
company: "Apple"
},
{
email: "Reek#yahoo.com",
password: "Reek123",
firstName: "Reek",
lastName: "Phaine",
contact: "876-277-2289",
role: "Supplier-User",
company: "Apple"
},
{
email: "Jim#yahoo.com",
password: "Jim123",
firstName: "Jim",
lastName: "Jones",
contact: "487-283-2489",
role: "Supplier-User",
company: "Apple"
}
];
localStorage.setItem("users", JSON.stringify($scope.users));
} else {
$scope.users = JSON.parse(localStorage.getItem("users"));
}
//Deleting a user.
$scope.deleteUser = function(user) {
$scope.clickedUser = user;
console.log($scope.users.indexOf($scope.clickedUser));
$scope.users.splice($scope.users.indexOf($scope.clickedUser), 1);
localStorage.setItem("users", JSON.stringify($scope.users));
$scope.info = "User Deleted Successfully!";
};
$scope.clearInfo = function() {
$scope.user = "";
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>User Management- M&M</title>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/userApp.js"></script>
</head>
<body ng-app="myApp" ng-controller="myController">
<div>
<input type="text" placeholder="Search Users" ng-model="searchUsers.email">
<button ng-click="search = searchUsers" type="button">Search</button>
</div>
<hr>
<table border="1">
<thead>
<tr class="table100-head">
<th>Email</th>
<th>First Name</th>
<th>Last Name</th>
<th>Contact</th>
<th>Role</th>
<th>Company</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users | filter: {'email':search.email} track by $index">
<td>{{user.email}}</td>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
<td>{{user.contact}}</td>
<td>{{user.role}}</td>
<td>{{user.company}}</td>
<td>
<button ng-click="deleteUser(user)" type="button">Delete</button>
</td>
</tr>
</tbody>
</table>
</body>
</html>
In first attempt your search.email was undefined, and when you clicked on search your search.email got defined, so next time on wards when you type something the default two way data binding was triggering the search.
In the below code snippet I have added a new function
$scope.searchUser = function(userEmail){
$scope.searchEmail = userEmail
}
and only when the user clicks on the button I am actually binding with the $scope which is triggering the search. Also added an onChange event where if the user erase up the text it resets the search
var myApp = angular.module("myApp", []);
myApp.controller("myController", function($scope) {
console.log("in controller...");
$scope.newUser = {};
$scope.info = "";
// Users array list
$scope.users = [{
email: "Vai#yahoo.com",
password: "Sha123",
firstName: "Vai",
lastName: "LSha",
contact: "123-223-8989",
role: "Super-Admin",
company: ""
},
{
email: "John#yahoo.com",
password: "John123",
firstName: "John",
lastName: "Doe",
contact: "281-283-2480",
role: "Supplier-Admin",
company: "Apple"
},
{
email: "Rick#yahoo.com",
password: "Rick123",
firstName: "Rick",
lastName: "Fraiser",
contact: "987-283-2489",
role: "Supplier-User",
company: "Apple"
},
{
email: "Reek#yahoo.com",
password: "Reek123",
firstName: "Reek",
lastName: "Phaine",
contact: "876-277-2289",
role: "Supplier-User",
company: "Apple"
},
{
email: "Jim#yahoo.com",
password: "Jim123",
firstName: "Jim",
lastName: "Jones",
contact: "487-283-2489",
role: "Supplier-User",
company: "Apple"
}
];
//Deleting a user.
$scope.deleteUser = function(user) {
$scope.clickedUser = user;
console.log($scope.users.indexOf($scope.clickedUser));
$scope.users.splice($scope.users.indexOf($scope.clickedUser), 1);
localStorage.setItem("users", JSON.stringify($scope.users));
$scope.info = "User Deleted Successfully!";
};
$scope.clearInfo = function() {
$scope.user = "";
};
$scope.searchUser = function(userEmail){
$scope.searchEmail = userEmail
}
$scope.onChange = function(){
if($scope.email.length === 0){
$scope.searchEmail = "";
$scope.email = "";
}
}
});
<html lang="en">
<head>
<meta charset="utf-8">
<title>User Management- M&M</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myController">
<div>
<input type="text" placeholder="Search Users" ng-change="onChange()" ng-model="email">
<button ng-click="searchUser(email)" type="button">Search</button>
</div>
<hr>
<table border="1">
<thead>
<tr class="table100-head">
<th>Email</th>
<th>First Name</th>
<th>Last Name</th>
<th>Contact</th>
<th>Role</th>
<th>Company</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users | filter: {'email': searchEmail} track by $index">
<td>{{user.email}}</td>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
<td>{{user.contact}}</td>
<td>{{user.role}}</td>
<td>{{user.company}}</td>
<td>
<button ng-click="deleteUser(user)" type="button">Delete</button>
</td>
</tr>
</tbody>
</table>
</body>
</html>
All together HTML with js work for custom filter. Here I am taking example of books with click filter when we click on subject name it filter
angular.module('testApp', []).controller('namesCtrl', function($scope) {
$scope.names = [{
name: 'Hindi'
},
{
name: 'Math'
},
{
name: 'English'
},
{
name: 'Science'
},
{
name: 'Computer'
},
{
name: 'History'
},
];
$scope.orderByMe = function(x) {
$scope.myOrderBy = x;
}
});
HTML Code
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<font size="3" color="red">
<p>Click the table headers to change the sorting order:</p>
</font>
<div ng-app="testApp" ng-controller="namesCtrl">
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Subject Name</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy">
<td>{{x.name}}</td>
</tr>
</table>
</div>
I am new to angularjs. I want to display the data in the following json file using ng-repeat.
http://www.cricbuzz.com/api/match/current
But I'm confused as there is a number in the data as key to each object. Can someone help me?
THis is a basic way to do it
Partial
<div ng-controller="Ctrl" >
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in rows">
<td>#{{ row.id}}</td>
<td>{{ row.series.name | uppercase }}</td>
</tr>
</tbody>
</table>
</div>
Controller
angular.module('app').controller('Ctrl', ['$scope', 'Resource', function ($scope, Resource) {
var pageChanged = function () {
$scope.myPromise = Resource.get({}, function (response) {
$scope.rows = response;
});
};
pageChanged();
}])
.factory('Resource', ['$resource', function($resource) {
return $resource('http://www.cricbuzz.com/api/match/current', {
}, {
'get': {
method: 'GET',
headers: {"Content-Type": "application/json"}
}
});
}]);
I am developing ASP.Net mvc 4 Application using EF .
This is Client/index.cshtml (Before Adding ExtJS)
#model IEnumerable<Proj.Client>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name_Clt)
</th>
<th>
#Html.DisplayNameFor(model => model.LName_Clt)
</th>
<th>
#Html.DisplayNameFor(model => model.Birthday_Clt)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name_Clt)
</td>
<td>
#Html.DisplayFor(modelItem => item.LName_Clt)
</td>
<td>
#Html.DisplayFor(modelItem => item.Birthday_Clt)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID_Client }) |
#Html.ActionLink("Details", "Details", new { id=item.ID_Client }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID_Client })
</td>
</tr>
}
</table>
I was following this blogpost , But I couldn't load data on it .
http://cincolabs.com/2012/04/10/asp-net-mvc-4-ext-js-4-gridpanel/
I created another ClientController .
public JsonResult GetUsers()
{
var entities = new Entities();
//What is important is to return the data as JSON.
return Json(entities.Clients.ToList(), JsonRequestBehavior.AllowGet);
}
Should I remplace this code .
public ActionResult Index()
{
var db = new Entities();
return View(db.Clients.ToList());
}
Another Question :
// Set up a model to use in our Store
Ext.define('Client', {
extend: 'Ext.data.Model',
fields: [
{ name: 'First_Name', type: 'string' },
{ name: 'Last_Name', type: 'string' },
{ name: 'Email', type: 'string' },
{ name: 'Date_Created', type: 'date', dateFormat: 'MS'}
]
});
var userStore = Ext.create('Ext.data.Store', {
model: 'Client',
proxy: {
type: 'ajax',
url: '/Examples/GetUsers',
reader: {
type: 'json',
root: 'users'
}
},
autoLoad: true
});
What does this mean "url: '/Examples/GetUsers'," !! Should I replace it in my case !!
Your first question is a bit vague. I never worked with Ext JS but from your posted code, it seems to me that it creates it own table using the GetUsers function. The first View you posted is an Index View that Visual Studio can automatically create that displays your data. If your Ext JS is creating the table, then I suggest you replace Index View with the appropriate code to call the table data. Then the method GetUsers should be renamed as Index.
Your question regarding /Examples/GetUsers should be the url to the controller method that saves your data (something like /Client/Save).