I have an object I want to put in a table.
the object seems like: {"text":"111","order":["1","2","3","4","5"]}
there may be array as well as simple strings.
So how can I put this object in a table if I want the table to look like this:
property value
text 111
order 1,2,3,4,5
My table shows in the value column ["1","2","3","4","5"] instead of 1,2,3,4,5.
Here is what I wrote:
<tr data-ng-repeat="(key,val) in object">
<td>
{{ key }}
</td>
<td>
{{val}}
</td>
</tr>
I also tried with ng-swtich but it didn't work.
Here is a sample which checks if the value is an Array and joins them as a string.
Html:
<tr data-ng-repeat="(key,val) in object">
<td>
{{ key }}
</td>
<td>
{{val | isArray}}
</td>
</tr>
Controller:
app.controller('MainCtrl', function($scope) {
$scope.object = {"text":"111","order":["1","2","3","4","5"]};
});
app.filter("isArray", function() {
return function(input) {
var isArray = angular.isArray(input);
if(isArray)
return input.join();
return input;
};
});
Working code here
Is this what you were after?
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-app="app" ng-controller="MyTableController">
<tr data-ng-repeat="(key,val) in data">
<td>
{{ key }}
</td>
<td >
{{ val | join: ', ' }}
</td>
</tr>
</table>
<script>
angular.module('app', [])
// Filter that joins the input with the supplied separator
.filter('join', function () {
return function (value, separator) {
if (typeof value.join === 'function') {
return value.join(separator);
} else {
return value;
}
}
})
.controller('MyTableController', function ($scope) {
$scope.data = {"text":"111","order":["1","2","3","4","5"] };
});
</script>
Related
I am trying to change the code that every time a user edits the marks in English or Hindi and then the highest Hindi and/or English marks are updated accordingly
CONTROLLER CODE
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope)
{
$scope.names = [
{name:'Priya',age:'19',gender:'Female',English:x[0], Hindi:x[1]},
....
....
{name:'Dev', age:'18' ,gender:'Male',English:x[2] ,Hindi:x[3]},
];
$scope.sum = function(list)
{
var total=0;
angular.forEach(list , function(x){
total+= x[];
});
return total;
}
});
HTML CODE
This is the code I use currently for displaying the highest marks
<tr ng-repeat ="x in names | orderBy:'sortColumn'">
<td>{{x.name}}</td>
<td>{{x.age}}</td>
<td>{{x.gender}}</td>
<td><input type="text" ng-model="x.English"></td>
<td><input type="text" ng-model="x.Hindi"></td>
<td ng-bind="avg=(x.English+x.Hindi)/2">{{avg}}</td>
<td>
<button>Delete</button>
</td>
</tr>
</table>
<table ng-model="sum">
<tr><td>The total is: <input value="{{sum(x)}}"></td></tr>
**<tr><td>THIS IS WHERE I WANT TO DISPLAY HIGHEST MARKS IN ENGLISH</td></tr>**
**<tr><td>**<td ng-repeat="x in names |orderBy:'-Hindi' | limitTo:1"> {{x.name}}THIS IS WHERE I WANT TO DISPLAY HIGHEST MARKS IN HINDI</td></tr>**
</table>
You can put watch on array like below:
$scope.total = 0
$scope.$watch('names', function(newVal) {
var total = 0;
angular.forEach(newVal, function(x) {
total += parseInt(x.English) + parseInt(x.Hindi);
});
$scope.total = total
}, true);
and in template replace {{sum(x)}} with {{total}}.
Check working example here
I have a table created in angularJS.
HTML:
<div class="widget-content" ng-controller="getAllBenchersController">
<table ng-table="talentPoolList" show-filter="true"
class="table table-striped table-bordered">
<tr ng-repeat="employee in $data" | filter: testFilter">
<td data-title="'#'">{{$index + 1}}</td>
<td data-title="'Employee ID'" sortable="'employee.employeeNo'"
filter="{ 'employee.employeeNo': 'text' }">
{{employee.employee.employeeNo}}
</td>
<td data-title="'Current State'" sortable="'state.state'" filter="{ 'state.state': 'text' }"
ng-class="{ red: employee.state.state == 'Available', blue: employee.state.state == 'Blocked'}">
{{employee.state.state}}
</td>
</tr>
</table>
</div>
In the <td data-title="'Current State'">I want to apply a filter. I want to display only states returning values 'Available' and 'Blocked'.
My controller is :
myApp.controller('getAllBenchersController', ['$scope', 'employeeTalentPoolServices', 'dataTable', '$window', '$timeout', function ($scope, employeeTalentPoolServices, dataTable, $window, $timeout) {
employeeTalentPoolServices.getAllBenchers().then(function (result) {
$scope.data = result.data;
$scope.testFilter = function (item) {
return (item.state.state.toLowerCase() === 'available' || item.state.state.toLowerCase() === 'blocked');
}
});
The states generally return values -'Available', 'Blocked', 'Billed' and 'Rejected'. I want the table to only display states - 'Available' and 'Blocked'.
Please have a check and point out what I'm doing wrong.
If you want to display only the items with the state 'available' and 'blocked' i think the best choice is to apply an angular filter in the ng-repeat. By this way, the ng-repeat only computes the items needed for the table.
You can add a new filter, for example:
myApp.filter('filterState',
[], function() {
return function(items) {
return items.map(function(obj) {
if (obj.state === 'available' || obj.state === 'blocked')
return obj;
});
});
After, your div element should be:
<tr ng-repeat="employee in $data" | filter: filterState">
return (item.state.state.toLowerCase() === 'available' || item.state.state.toLowerCase() === 'blocked');
Above code returns a boolean value, also if you have array list of values , here only one value is considered.
You should write a for loop , then check the values.
Refer below code:
var filteredOutput=[];
for(var i=0;i<item.length; i++){
if(item[i].state.state.toLowerCase() === 'available' || item[i].state.state.toLowerCase() === 'blocked')
{
filteredOutput.push(item[i]);
}
}
return filteredOutput;
I am getting the below error while using angular.js filter methos.
Error:
TypeError: Cannot read property 'length' of undefined
at adminCustomerViewController.js:1387
at fn (eval at compile (angularjs.js:212), <anonymous>:4:464)
at dirPagination.js:100
at Object.<anonymous> (angularjs.js:115)
at n.$digest (angularjs.js:130)
at n.$apply (angularjs.js:133)
at g (angularjs.js:87)
at K (angularjs.js:91)
at XMLHttpRequest.z.onload (angularjs.js:92)
I am explaining my code below.
<input class="form-control" placeholder="Type Restaurant Name" name="q" type="text" ng-model="letter">
<tr dir-paginate="cus in ($parent.labelResults=(listOfCustomerData | startsWithLetter:letter | orderBy:'rest_name')) | itemsPerPage:5 track by $index" current-page="currentPage">
<td>{{itemsPerPage *(currentPage-1)+$index+1}}</td>
<td>{{cus.rest_name}}</td>
</tr>
</tbody>
My controller side code is given below.
customerView.filter('startsWithLetter', function () {
return function (items, letter) {
//console.log('items',items);
var filtered = [];
var letterMatch = new RegExp(letter, 'i');
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (letterMatch.test(item.rest_name.substring(0, 1))) {
filtered.push(item);
}
}
return filtered;
};
});
customerView.controller('adminCustomerViewController',function($scope,$state,$http,$window,$timeout,Upload,focusInputField){
$http({
method:'GET',
url:"php/customerInfo.php?action=disp",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
console.log('res',response.data);
$scope.listOfCustomerData=response.data;
},function errorCallback(response) {
})
})
Actually i am implementing the search functionality here . Here my requirement is when user will type at least first letter of the restaurant name(i.e-rest_name) the related restaurant will filter from the table. Suppose i have many restaurant like Anjum,A&P Chinese Food Express,Bookers BBQ & Crab Shack,Butcher And The Baker, Cactus Club Stephen Avenue,Cactus Club - Macleod Trail. Here when user is typing only a inside the search box the names started with a should filter . I did something but got the above error.Please help me.
Since you want only those objects that have the corresponding letters to input
you don't need to use Regexp.
Here a snippet working:
var app = angular.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.countries = [
{
"name":"USA"
},
{
"name":"Japan"
},
{
"name":"France"
},
{
"name":"Canada"
},
{
"name":"China"
}
];
})
.filter('startsWith', function() {
return function(items, search) {
if (!search) {
return items;
}
search = search.toLowerCase();
return items.filter(function(element) {
return element.name.toLowerCase().substring(0, search.length).indexOf(search) != -1;
});
}
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<label for="letter">Filter: </label>
<input type="text" id="letter" ng-model="letter">
<hr>
<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="country in countries | startsWith: letter">
<td ng-bind="country.name"></td>
</tr>
</tbody>
</table>
</body>
</html>
Try this
<input class="form-control" placeholder="Type Restaurant Name" name="q" type="text" ng-model="letter">
<tr dir-paginate="cus in ($parent.labelResults=(listOfCustomerData | filter : letter )) | itemsPerPage:5 track by $index" current-page="currentPage">
<td>{{itemsPerPage *(currentPage-1)+$index+1}}</td>
<td>{{cus.rest_name}}</td>
</tr>
</tbody>
its best to use filter given in angular as comapred to make your custom filter
I am trying to highlight multiple row select functionality, so that when a user click's on a row it highlight the row and when it again select that row it un-highlight that. But the problem I am facing is how to give array of items to ng-class.
Here is my code.
<tr ng-click="selectRow(1)" ng-class="{row_selected: ArrayOfItems}" class="ng-scope odd">
<td class="">
test
</td>
</tr>
And in my controller
$scope.selectedArray = [];
$scope.selectRow = function(id) {
if($scope.selectedArray.indexOf(id) == -1) {
$scope.selectedArray.push(id);
}else {
$scope.selectedArray.splice($scope.selectedArray.indexOf(id),1);
}
});
So what I am doing in controller is on clicking a row it push the id's in an array and on clicking the same row it pops out that id from array.
Any help ?
First check whether the row is selected or not
<tr ng-click="selectRow(1)" ng-class="{row_selected: isRowSelected(1)}" class="ng-scope odd">
<td class="">
test
</td>
</tr>
Add the isRowSelected to controller:
$scope.selectedArray = [];
$scope.isRowSelected = function(id) {
$scope.selectedArray.indexOf(id) != -1
}
$scope.selectRow = function(id) {
if($scope.selectedArray.indexOf(id) == -1) {
$scope.selectedArray.push(id);
}else {
$scope.selectedArray.splice($scope.selectedArray.indexOf(id),1);
}
});
More proper setup would be with in use of 'ng-repeat'. See the working code at:
JSFiddle
HTML:
<div ng-controller="MyController">
<table>
<tr ng-repeat="item in items" ng-click="selectRow(item)" ng-class="{row_selected: isSelected(item)}">
<td>
<a id="{{item}}">test {{item}}</a>
</td>
</tr>
</table>
</div>
JS/AngularJS:
var myApp = angular.module('myApp', []);
myApp.controller('MyController', ['$scope', function ($scope) {
$scope.items = [1,2,3,4,5];
$scope.selectedArray = [];
$scope.selectRow = function (id) {
if($scope.selectedArray.indexOf(id) == -1) {
$scope.selectedArray.push(id);
}else {
$scope.selectedArray.splice($scope.selectedArray.indexOf(id),1);
}
};
$scope.isSelected = function (id) {
if( $scope.selectedArray.indexOf(id) > -1){
return true;
}
return false;
};
}]);
I have a list with items. Each item of a list can be selected. If I select the item, it will be pushed in the cookies.
In my home.html (here I have the list with the items that I can add to cookies)
<table class="table" >
<tr data-ng-repeat="item in items">
<td><span >{{item.title}}</span></td>
<td> <button data-ng-click="addToCookies(item)" data-ng-disabled="item.added" class="btn">
<span data-ng-show="!item[$index].added" class="text-center">Add To cookies</span>
<span data-ng-show="item[$index].added" class="text-center">Added To cookies</span>
</button>
</td>
</tr>
<tr></tr>
</table>
In page cookies.html I call the getCookiesItem() and the directive :
<div class="navbar navbar-right" data-ng-controller="ctrlItemsList">
<div data-item-list data-items="getCookiesItem()" ></div>
</div>
In my controller I did :
//TO ADD ELEMENT SELECTED IN THE COOKIE
$scope.addToCookies = function (item){
item.added=true;
angular.extend($scope.criteria, item);
cookiesItems.addItem($scope.criteria);
}
//TO GET ELEMENTS COOKIE (MAYBE I HAVE TO DO A $WATCH OF THIS FUNCTION)
$scope.getCookiesItem = function (){
return cookiesItems.getItems();
}
In my service I have :
Cservices.factory('cookiesItems', ['$cookieStore', function($cookieStore) {
var items = [];
return {
addItem: function( itemSelected){
var array = [];
if ($cookieStore.get('key') === undefined) {
$cookieStore.put('key', []);
}else{
array = $cookieStore.get('key');
}
array.push(itemSelected);
$cookieStore.put('key', array);
},
removeItem: function(itemSelected){
var array = $cookieStore.get('key');
if(array != undefined){
for (var i = 0; i < array.length; ) {
if (array[i].id=== itemSelected.id) {
array.splice(array[i], 1);
} else {
++i;
}
}
}
$cookieStore.put('key', array);
},
getItems: function(){
return $cookieStore.get('key');
}
The elements cookies are print in the following directive:
template :
<table class="table" >
<tr data-ng-repeat="item in items">
<td>{{item.title}}</td>
</tr>
<tr></tr>
</table>
in the js :
iDirective.directive('itemList', function() {
return {
restrict: 'A',
transclude: true,
scope: {
items: '=items'
}
templateUrl: ''
};
});
I have the following error:
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [["fn: parentValueWatch; newVal: [{
and when i try to add the 10' element in the cookies I have this error (only 9 element I am able to store): Cookie '' possibly not set or overflowed because it was too large (4263 > 4096 bytes)! -
I am not able to resolve it..someone can help me?
Thanks
It would be helpful if you could put together a jsfiddle example.
From your code I can see the following issue.
In the ng-repeat section either should use 'items[$index]' or just 'item'.
<table class="table" >
<tr data-ng-repeat="item in items">
<td><span >{{item.title}}</span></td>
<td> <button data-ng-click="addToCookies(item)" data-ng-disabled="item.added" class="btn">
<span data-ng-show="!item.added" class="text-center">Add To cookies</span>
<span data-ng-show="item.added" class="text-center">Added To cookies</span>
</button>
</td>
</tr>
<tr></tr>
</table>
What is the method addToCookies exactly doing? What is $scope.criteria object? It looks like you always modify and add the same object to the cookieItems.
$scope.addToCookies = function (item){
item.added=true;
angular.extend($scope.criteria, item); // what is $scope.criteria?
cookiesItems.addItem($scope.criteria); // will always the same object added to the cookieItems?
$scope.selectedItems.push(item); // why do you have a second list and why you add 'item' and not 'criteria'?
}