Length angular of items in ng-repeat - javascript

First, I have this table:
Where you can see, different colours in the column estado. There are 4 different cases. And i Want to count this different cases. For example in this case there are: Active(green): 1, Vodafone(green+logo): 1, Desactive(Red): 1, Pending(orange):1. But it can change depend of the case.
<div class="input-group">
<div> <h>Instalaciones: {{filteredsites.length}}</h> <h>Active: {{}}</h> <h>Vodafone: {{}}</h> <h>Desactive: {{}}</h> <h>Pending: {{}}</h></div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-3">
<div >
<table class="table table-bordered table-hover table-responsive table-striped dataTable no-footer" data-sort-name="name" data-sort-order="desc">
<tr role = "row" class="info text-center">
<th ng-click="order('msisdn')">Número Teléfono</th>
<th ng-click="order('icc')">ICC</th>
<!--th>IMEI</th-->
<th ng-click="order('ActivationStatus')">Estado</th>
<th ng-click="order('sitename')">Instalación</th>
<th ng-click="order('siteaddress')">Dirección</th>
<th ng-click="order('sitecity')">Ciudad</th>
<th ng-click="order('sitezip')">Código Postal</th>
<th ng-click="order('phonedesc')">Modelo Teléfono</th>
</tr>
<tr class=" text-center" ng-repeat-start="object in filteredsites = (objects | filter:searchText | filter:{parentgroupid:selectedgroup||undefined}) | filter:tableFilter| orderBy:predicate:reverse" ng-click="showDetails = ! showDetails" >
<td>{{object.msisdn}}</td>
<td>{{object.icc}}</td>
<!--td>{{object.ActivationStatus}}</td-->
<td><span ng-init="getStatusCount(object.ActivationStatus)" ng-show="object.ActivationStatus=='AC' && object.ContractingMode=='0'" class="fa fa-square fa-3x"style="color:lime"></span><span ng-show="object.ContractingMode=='2' && object.ActivationStatus=='AC' " ><img src="../img/Vodafone_logo.png" width="40" height="40" style="background-color: lime"></span><span ng-show="object.ActivationStatus=='PA'" class="fa fa-square fa-3x"style="color:yellow"></span><span ng-show="object.ActivationStatus=='DE'" class="fa fa-square fa-3x"style="color:red"></span></td>
<td>{{object.sitename}}</td>
<td>{{object.siteaddress}}</td>
<td>{{object.sitecity}}</td>
<td>{{object.sitezip}}</td>
<td><span ng-show="object.phonedesc==''"></span><span ng-show="object.phonedesc=='Desconocido'">Desconocido</span><span></span>{{getPhoneModel(object.phonedesc)}}</td>
</tr>
</table>
</div>
<!-- /.table-responsive -->
</div>
<!-- /.col-lg-4 (nested) -->
<!-- /.col-lg-8 (nested) -->
</div>
And the controller:
var app = angular.module('dashboard', ['ui.bootstrap']);
app.controller('dashboardController', function ($scope, $http, $modal) {
$scope.objects = [];
$scope.grupos = [];
$scope.longitud = [];
$scope.eventos = [];
var URL = "/api/auth/logout";
var URLOperation = "/api/sites";
var URLModel = "http://localhost:81/api/phonelist/";
$scope.getStatusCount= function (status){
// console.log(status);
var active = 0;
active++;
console.log(active);
angular.forEach(status ,function(obj) {
if (obj.status == status) {
console.log(obj.status);
console.log(status);
console.log(active);
active++;
console.log(active);
} });
}
//Funci?n que devuelve las instalaciones de un usuario
$http.get(URLOperation, $scope)
.success(function (data) {
var groups = data;
angular.forEach(groups, function (group) {
var group2 = group;
angular.forEach(group2.sites, function (group3) {
$scope.longitud.push(group3);
$scope.objects.push(group3);
$scope.predicate = 'msisdn';
$scope.reverse = true;
$scope.order = function (predicate) {
$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
$scope.predicate = predicate;
};
})
});
})
.error(function (data) {
window.alert('Something Wrong...');
});
});
If someone can help me the count the different ActivationStatus cases i will appreciated.

You pretty much had it correct? I worked on your example in plunker and it worked right off the bet?
ng-show="object.ActivationStatus=='AC' && object.ContractingMode=='0'"
Seemed to be working for me.

Related

grid sorting in AngularJs

I am very new to AngularJs.
I got the data in table using ng-repeat.
Now, i am trying to sort the table columns. It is not happening.
Please give me the suggestion.
<html ng-app="authorsApp">
<div ng-controller="myAuthors">
<table class="table table-striped table-hover">
<tr>
<th ng-click="sort{'name'}">
Name
<span class="glyphicon glyphicon-sort" ng-show="sortKey == 'name'" ng-class="{'glyphicon-chevron-up':reverse, 'glyphicon-chevron-down':!reverse}"></span>
</th>
<th ng-click="sort{'department'}">
Deparment
<span class="glyphicon glyphicon-sort" ng-show="sortKey == 'department'" ng-class="{'glyphicon-chevron-up':reverse, 'glyphicon-chevron-down':!reverse}"></span>
</th>
</tr>
<tr ng-repeat="auther in authors | filter: search | orderBy:sortKey:reverse">
<td>{{auther.name}}</td>
<td>{{auther.department}}</td>
</tr>
</table>
</div>
<script src="Scripts/angular.js"></script>
<script src="Assets/js/authors-01.js"></script>
</html>
js file as below
var app = angular.module("authorsApp", []);
app.controller("myAuthors", function ($scope, $http) {
$scope.authors = [];
$http.get('Assets/js/authors-01.json').then(function (response) {
$scope.authors = response.data;
});
$scope.sort = function (keyname) {
$scope.sortKey = keyname;
$scope.reverse = !$scope.reverse;
}
});
json file as below
[
{
"name": "Manoj",
"department": "Design"
},
{
"name": "Srikant",
"department": "Business"
}
]
Thanks in advance.
In the view, as set in the comments by #tanmay, you should call sort() instead of sort{}
Code example:
angular
.module("authorsApp", [])
.controller("myAuthors", function ($scope) {
// Authors for code example...
$scope.authors = [{"name": "Manoj","department": "Design"},{"name": "Srikant","department": "Business"}];
$scope.sort = function (keyname) {
$scope.sortKey = keyname;
$scope.reverse = !$scope.reverse;
}
});
th { cursor: pointer; }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="authorsApp" ng-controller="myAuthors">
<table class="table table-striped table-hover">
<tr>
<th ng-click="sort('name')">
Name
<span class="glyphicon glyphicon-sort" ng-show="sortKey == 'name'" ng-class="{'glyphicon-chevron-up':reverse, 'glyphicon-chevron-down':!reverse}"></span>
</th>
<th ng-click="sort('department')">
Deparment
<span class="glyphicon glyphicon-sort" ng-show="sortKey == 'department'" ng-class="{'glyphicon-chevron-up':reverse, 'glyphicon-chevron-down':!reverse}"></span>
</th>
</tr>
<tr ng-repeat="auther in authors | filter: search | orderBy:sortKey:reverse">
<td>{{auther.name}}</td>
<td>{{auther.department}}</td>
</tr>
</table>
</div>

How to select and deselect an div / button in angularJs?

I am trying to make items not in list but in div and if an item is clicked, the div will be in different colors and the item will be added into a column but if the item is clicked again, the item will changed to original color and in the column the item will be gone. I just can't think how to do it in angular way. I came to another option to be able to add in the column and to remove the item, there's a remove button but I am still curious how the select and deselect can be done.
This is what I have in my html (ignore my btn btn-primary classes I was using button to give it a try in the first place)
<!--Select App Features-->
<div class="panel-heading" ng-controller="FeaturesController as featuresCtrl">
<h1 class="text-center">App Features</h1>
<div class="text-center">
<div ng-repeat="app in featuresCtrl.apps" class="btn btn-primary platform-btn-style" ng-click="featuresCtrl.addPrices(app.name, app.price)">{{ app.name }}</div><br>
</div>
<div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Device Added</th>
<th>Device Price</th>
<th></th>
</tr>
</thead>
<tr ng-repeat="appList in featuresCtrl.listAppPrices">
<td>{{ appList.name }}</td>
<td>{{ appList.price }}</td>
<td><button class="btn btn-default" ng-click="featuresCtrl.remove($index)">Remove</button></td>
</tr>
</table>
<div>Total : {{ featuresCtrl.totalAppPrice() }}</div>
</div>
</div><!-- end select app features / FeaturesController-->
My controller in js
//Controller for app features
app.controller("FeaturesController", function(){
this.apps = features;
this.listAppPrices = [];
// add name and price into the new array which is used to show in the table
this.addPrices = function(name, price){
//Checks if the exact name, price property exists in the array and return boolean
var found = this.listAppPrices.some(function (e){
console.log(e.name);
return ((e.name === name) && (e.price === price)) ;
});
//If found not true then push the new values into the array
if(!found){
this.listAppPrices.push({name: name, price: price});
}
};
// adds all the prices of the array which gives the total
this.totalAppPrice = function(){
var total = 0;
for(var i = 0; i < this.listAppPrices.length; i++){
total += this.listAppPrices[i].price;
}
return total;
};
// remove the whole object in the array when remove is clicked
this.remove = function(index) {
this.listAppPrices.splice(index, 1);
};
});
I kind of having the idea of how this can be done but I just can't think of the code to write it.
P.S. the codes are simple, I just learned it in code school and wanted to created something for fun to educate myself. Thanks in advance people
angular.module("stack", [])
.controller("FeaturesController", function($scope) {
// this.apps = features;
this.listAppPrices = [];
this.apps = [{ "name": "a1", "price": "12" }, { "name": "a2", "price": "13" }, { "name": "a3", "price": "14" }];
$scope.dummyArray = [];
var f = 0,
x = 0,
rem = false;
this.setSelected = function(app, index) {
console.log("app ", app);
//remove an item
if (app.selected) {
console.log(" list ", $scope.dummyArray);
$scope.dummyArray.forEach(function(e, ind) {
if (e.name === app.name) {
console.log(ind, " e ", e);
rem = true;
$scope.dummyArray.splice(ind, 1);
}
});
console.log("dumm ", $scope.dummyArray);
this.listAppPrices = $scope.dummyArray;
} else {
rem = false;
}
//used to select a div and change its colour
app.selected ? app.selected = false : app.selected = true;
//add an item
if (!rem) {
if ($scope.dummyArray.length) {
$scope.dummyArray.forEach(function(each) {
console.log("each ");
if (each.name !== app.name) {
console.log("inside if ");
f = 1;
}
});
} else {
console.log("inside else ");
$scope.dummyArray.push(app);
}
if (f === 1) {
f = 0;
console.log("push");
$scope.dummyArray.push(app);
}
console.log(" list--> ", $scope.dummyArray.length);
this.listAppPrices = $scope.dummyArray;
}
}
});
.selected {
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="stack">
<head>
<title>stack</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="panel-heading" ng-controller="FeaturesController as featuresCtrl">
<h1 class="text-center x">App Features</h1>
<div class="text-center">
<div ng-repeat="app in featuresCtrl.apps track by $index" class="btn btn-primary platform-btn-style" ng-click="featuresCtrl.setSelected(app,$index)" ng-class="{selected: app.selected}">{{ app.name }}</div>
<!-- <div ng-if="(c%2===0)" ng-repeat="app in featuresCtrl.apps" class="btn btn-primary platform-btn-style" ng-click="featuresCtrl.setSelected(app)">{{ app.name }}</div> -->
<br>
</div>
<div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Device Added</th>
<th>Device Price</th>
<th></th>
</tr>
</thead>
<tr ng-repeat="appList in featuresCtrl.listAppPrices">
<td>{{ appList.name }}</td>
<td>{{ appList.price }}</td>
<td>
<button class="btn btn-default" ng-click="featuresCtrl.remove($index)">Remove</button>
</td>
</tr>
</table>
<div>Total : {{ featuresCtrl.totalAppPrice() }}</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<script type="text/javascript" src="controller.js"></script>
</body>
</html>
I haven't added the functionality of remove button.I also haven't count the totalAppPrice. Otherwise your problem is solved :) .

Angular Error - ReferenceError: $modal is not defined

I am using code form a tutorial and modifying it a bit. I have run into an issue with the edit feature. I keep getting a "ReferenceError: $modal is not defined" here is my code.
postCtrl:
app.filter('startFrom', function() {
return function(input, start) {
if(input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
});
app.filter('dateToISO', function() {
return function(input) {
input = new Date(input).toISOString();
return input;
};
});
app.controller('postsCtrl', function ($scope, $log, $http, $timeout, Data) {
Data.get('posts').then(function(data){
$scope.posts = data.data;
$scope.currentPage = 1; //current page
$scope.filteredItems = $scope.posts.length; //Initially for no filter
$scope.totalItems = $scope.posts.length;
$scope.list_pages = [
{
id: '5',
name: '5'
}, {
id: '10',
name: '10'
}, {
id: '20',
name: '20'
}, {
id: '50',
name: '50'
}, {
id: '100',
name: '100'
}
];
$scope.maxSize = 5;
});
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.filter = function() {
$timeout(function() {
$scope.filteredItems = $scope.filtered.length;
}, 10);
};
$scope.sort_by = function(predicate) {
$scope.predicate = predicate;
$scope.reverse = !$scope.reverse;
};
$scope.changePostStatus = function(post){
post.approved = (post.approved=="1" ? "0" : "1");
Data.put("posts/"+post.id,{approved:post.approved});
};
$scope.changePostAnnounce = function(post){
post.announce = (post.announce=="1" ? "0" : "1");
Data.put("posts/"+post.id,{announce:post.announce});
};
$scope.trashPost = function(post){
//$log.log(post);
if(confirm("Are you sure to remove the post")){
Data.delete("posts/"+post.id).then(function(result){
$scope.posts = _.without($scope.posts, _.findWhere($scope.posts, {id:post.id}));
});
}
};
$scope.open = function (p,size) {
var modalInstance = $modal.open({
templateUrl: 'views/postsEdit.html',
controller: 'postsEditCtrl',
size: size,
resolve: {
item: function () {
return p;
}
}
});
modalInstance.result.then(function(selectedObject) {
if(selectedObject.save == "insert"){
$scope.posts.push(selectedObject);
$scope.posts = $filter('orderBy')($scope.posts, 'id', 'reverse');
}else if(selectedObject.save == "update"){
p.description = selectedObject.description;
p.price = selectedObject.price;
p.stock = selectedObject.stock;
p.packing = selectedObject.packing;
}
});
};
});
app.controller('postsEditCtrl', function ($scope, $modalInstance, item, Data) {
$scope.post = angular.copy(item);
$scope.cancel = function () {
$modalInstance.dismiss('Close');
};
$scope.title = (item.id > 0) ? 'Edit Post' : 'Add Post';
$scope.buttonText = (item.id > 0) ? 'Update Post' : 'Add New Post';
var original = item;
$scope.isClean = function() {
return angular.equals(original, $scope.post);
}
$scope.saveProduct = function (post) {
post.uid = $scope.uid;
if(post.id > 0){
Data.put('posts/'+post.id, post).then(function (result) {
if(result.status != 'error'){
var x = angular.copy(post);
x.save = 'update';
$modalInstance.close(x);
}else{
console.log(result);
}
});
}else{
post.status = 'Active';
Data.post('posts', post).then(function (result) {
if(result.status != 'error'){
var x = angular.copy(post);
x.save = 'insert';
x.id = result.data;
$modalInstance.close(x);
}else{
console.log(result);
}
});
}
};
});
html:
<div class="container">
<div class="row" align="center">
<div class="stats"><i class="fa fa-thumb-tack"></i> Total Posts (<span class="attendStat">{{ totalItems }}</span>)<span class="seperator"> | </span><i class="fa fa-trash-o"></i> Trash (<span class="attendStat">X</span>)</div>
</div>
<div class="row">
<div class="col-md-1">PageSize:
<select ng-model="entryLimit" class="form-control" ng-options="obj.id as obj.name for obj in list_pages" ng-init="entryLimit='10'">
</select>
</div>
<div class="col-md-5"><span class="">Filtered: {{ filtered.length }} of {{ totalItems }} total posts</span>
<input type="text" ng-model="search" ng-change="filter()" placeholder="Filter" class="form-control" />
</div>
<div class="col-md-4 pull-right text-right" ng-show="filteredItems > 0">
<uib-pagination total-items="filteredItems" items-per-page="entryLimit" boundary-link-numbers="true" max-size="maxSize" ng-model="currentPage" class="pagination-sm"></uib-pagination>
</div>
</div>
<br/>
<div class="row">
<div class="table-responsive" ng-show="filteredItems > 0">
<table class="table table-striped table-bordered">
<thead>
<th>Publish Date <a ng-click="sort_by('publishdate');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>GUID <a ng-click="sort_by('guid');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Platform <a ng-click="sort_by('platform');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Link Title <a ng-click="sort_by('title');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Redirect Url (Base) <a ng-click="sort_by('redirect');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Announce <a ng-click="sort_by('announce');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Approve <a ng-click="sort_by('approve');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th></th>
</thead>
<tbody ng-repeat="data in filtered = (posts | filter:search | orderBy : predicate :reverse) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit">
<tr>
<td class="posts-publishdate">{{data.publishdate | dateToISO | date:'MMM d, y h:mm a' }}</td>
<td>{{data.guid}}</td>
<td>{{data.platform}}</td>
<td>{{data.title}}</td>
<td>{{data.redirect}}</td>
<td>
<button class="btn btn-sm" ng-class="{1:'btn-success', 0:''}[data.announce]" ng-click="changePostAnnounce(data);">{{data.announce == '1' ? "Active" : "Inactive"}}</button>
</td>
<td>
<button class="btn btn-sm" ng-class="{1:'btn-success', 0:''}[data.approved]" ng-click="changePostStatus(data);">{{data.approved == '1' ? "Active" : "Inactive"}}</button>
</td>
<td style="width:100px">
<div class="btn-group">
<button type="button" class="btn btn-default fa fa-edit" ng-click="open(data);"></button>
<button type="button" class="btn btn-danger fa fa-trash-o" ng-click="trashPost(data);"></button>
</div>
</td>
</tr>
<tr>
<td></td>
<td colspan="8">
<table class="table table-striped table-bordered">
<thead>
<th>Image Url <a ng-click="sort_by('img');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Link Description <a ng-click="sort_by('description');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Tweet <a ng-click="sort_by('dynamic_content');"><i class="glyphicon glyphicon-sort"></i></a></th>
</thead>
<tbody>
<tr>
<td><img src="{{data.img}}" width="200"></td>
<td>{{data.description}}</td>
<td>{{data.dynamic_content}}</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-12" ng-show="filteredItems == 0">
<div class="col-md-12">
<h4>No customers found</h4>
</div>
</div>
</div>
</div>
Any help would be much appreciated.
You missed to inject $modal dependency inside postsCtrl controller
app.controller('postsCtrl', function ($scope, $log, $http, $timeout, Data, $modal) {
Make sure you have injected particular dependency before getting
access to it. Assuming you have already added ui.bootstrap module
dependency too.
UPDATE
If you are using latest version of angular ui bootstrap which is 0.14.X would need to inject $uibModal instead of $modal. As they rename all boostrap directive and serviec name prepends with uib prefix.
Same thing will happen with $modalInstance dependency, which need to change to $uibModalInstance

Filtering in nested array

I have a nested data structure mapped to array in knockout JS:
class Departments{
string DepartmentName;
List<Group> groups
}
class Group{
string groupName;
List<Person> persons;
}
class Person{
String Firsname;
string LastName;
}
I fetched data from server and show them in UI successfully. But I want convert the array to a computed one in knockoutJS and filter it by FirstName and LastName. It's worthy to mention I have bound self.search_FirstName and self.search_LastName to two different inputs. HTML code for binding data is as follow:
<div class="form-group">
<input type="text" class="text-right text-success input-lg" placeholder="Name" data-bind="value:search_FirstName, valueUpdate: 'afterkeydown'" />
</div>
<div class="panel-group" id="accordion" data-bind="foreach: Profiles" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title" data-bind="text: DepartmentName"></h4>
</div>
<div class="panel-collapse collapse in">
<div class="panel-body">
<table data-bind="foreach: { data: GroupVMs }" class="table table-responsive col-lg-12 col-sm-12 col-md-12">
<tbody>
<tr><td class="groups" data-bind="text: GroupName"></td></tr>
<tr>
<td>
<table data-bind="foreach: { data: PersonPhonesVMs }" class="table table-striped table-responsive col-lg-12 col-sm-12 col-md-12">
<tr>
<td class="col-lg-1 col-sm-1 col-md-1" data-bind="text: Prefix"></td>
<td class="col-lg-2 col-sm-2 col-md-2" data-bind="text: FirstName"></td>
<td class="col-lg-3 col-sm-3 col-md-3" data-bind="text: LastName"></td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
Now I want during typing in the text box search_FirstName data automatically be filtered. Right Now I can filter records based on DepartmentName with the following code:
self.Profiles = ko.computed(function () {
return ko.utils.arrayFilter(self.BackupProfiles(), function (rec) {
return (
(self.search_FirstName().length == 0 || rec.DepartmentName.indexOf(self.search_FirstName()) > -1)
);
});
});
Does anyone has any idea for filtering records based on firstname and lastname fields?
I have created a fiddle for you. The computed at the heart of it builds up a structure like the Profiles structure, but only including the matched records.
vm.filteredProfiles = ko.computed(function () {
var first = vm.search_FirstName().toLocaleLowerCase();
if (first === '') return vm.Profiles();
var result = [];
ko.utils.arrayForEach(vm.Profiles(), function (dept) {
var groupsMatched = [];
ko.utils.arrayForEach(dept.GroupVMs(), function (group) {
var personsMatched = [];
ko.utils.arrayForEach(group.PersonPhonesVMs(), function (person) {
if (person.FirstName().toLocaleLowerCase().indexOf(first) > -1) {
personsMatched.push(person);
}
});
if (personsMatched.length > 0) {
groupsMatched.push({
GroupName: group.GroupName,
PersonPhonesVMs: personsMatched
});
}
});
if (groupsMatched.length > 0) {
result.push({
DepartmentName: dept.DepartmentName,
GroupVMs: groupsMatched
});
}
});
return result;
});
If I understand correctly, you want to "flatten" the entire structure, so that you have an array of people with with DepartmentName and GroupName fields. For the computed to work, each level of your original structure must be observableArrays. The computed would be something like:
var flattenedPeople = ko.computed(function () {
var result = [];
ko.utils.arrayForEach(self.BackupProfiles(), function (dept) {
ko.utils.arrayForEach(dept.groups(), function (group) {
ko.utils.arrayForEach(group.persons(), function (person) {
result.push({
DepartmentName: dept.DepartmentName,
GroupName: group.GroupName,
FirstName: person.FirstName,
LastName: person.LastName
});
});
});
return result;
});
Then you could make a computed that would match on FirstName and/or Lastname:
self.filteredPeople = ko.computed(function () {
var first = self.search_FirstName(),
last = self.search_LastName();
return ko.utils.arrayFilter(flattenedPeople(), function (rec) {
return ( first === '' || rec.FirstName === first ) &&
(last === '' || rec.LastName === last );
});
});

AngularJS: table edit data + update server

I have managed to create a table using AngularJS. In this table I show products from my datbase which can be filtered on category or some other keywords. Now the user should be able to alter this data in this table to update the data in the database.
AngularJS
categorieFilter = angular.module("categorieFilter", [])
categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){
$scope.search = "";
$scope.products = [];
$scope.categories = [];
store.getCategories().then(function(data){
$scope.categories = data;
})
store.getProducts().then(function(data){
$scope.products = data;
})
$scope.filterProductsByCats = function(category){
$scope.search = category;
};
}])
categorieFilter.factory('store', function($http, $q){
function _getCategory (){
var deferred = $q.defer();
$http.get('api/categories').success(function (data) {
deferred.resolve(data);
})
return deferred.promise;
}
function _getProducts (){
var deferred = $q.defer();
var prods = [];
$http.get('api/products').success(function (data) {
for(var i = 0;i<data.length;i++)
{
prods[i] = {name: data[i][0], category: data[i][2], price: data[i][1]};
}
deferred.resolve(prods);
})
return deferred.promise;
}
return {
getCategories: _getCategory,
getProducts : _getProducts
};
});
HTML table
<div ng-app="categorieFilter" ng-cloak="" ng-controller="catFilter">
<div class="input-group">
<input type="text" name="table_search" class="form-control input-sm pull-right" ng-model="search" placeholder="Search"/>
<div class="input-group-btn">
<button class="btn btn-sm btn-default">
<i class="fa fa-search"></i>
</button>
</div>
</div>
<div>
<input type="submit" class="btn btn-success" style="margin:10px; width:30%;" ng-repeat="cat in categories" ng-click="filterProductsByCats(cat.categoryName)" value="{{cat.categoryName}}">
</div>
<table class="table table-hover">
<tr style="background-color:#ddd;">
<th colspan="4" style="text-align:left; font-size:16px;"> Category </th>
<th colspan="4" style="text-align:left; font-size:16px;"> Product </th>
<th colspan="4" style="text-align:left; font-size:16px;"> Price </th>
</tr>
<tr ng-repeat="product in products | filter:search | orderBy: 'category'">
<td colspan="4">{{product.category}}</td>
<td colspan="4">{{product.name}}</td>
<td colspan="4">{{product.price}}</td>
</tr>
</table>
Any ideas or reccomendations to get this done?
A library I like to use to achieve the editing of data, is angular xeditable. http://vitalets.github.io/angular-xeditable/
Then save it by posting it back to the webapi

Categories

Resources