I have sample Json. I am fiter based on key value.
The fiter didn't sort exact value
Example:
angular.module('myApp').controller('testController', ['$filter', '$scope',
function($filter, $scope) {
var obj = '[{"id":"1","m_id":1,"value":"Male"},
{"id":"2","m_id":1,"value":"Female"},
{"id":"3","m_id":1,"value":"Other"},
{"id":"45","m_id":9,"value":"Single"},
{"id":"46","m_id":9,"value":"Married"},
{"id":"47","m_id":10,"value":"Father"},
{"id":"48","m_id":10,"value":"Mother"},
{"id":"61","m_id":10,"value":"Cousin"},
{"id":"62","m_id":10,"value":"Other"}]';
var obj1 = JSON.parse(obj);
var result = $filter('filter')(obj1, {
m_id : "1"
});
}]);
Output:
[{"id":"1","m_id":1,"value":"Male"},
{"id":"2","m_id":1,"value":"Female"},
{"id":"3","m_id":1,"value":"Other"},
{"id":"47","m_id":10,"value":"Father"},
{"id":"48","m_id":10,"value":"Mother"},
{"id":"61","m_id":10,"value":"Cousin"},
{"id":"62","m_id":10,"value":"Other"}]
Expected Output:
[{"id":"1","m_id":1,"value":"Male"},
{"id":"2","m_id":1,"value":"Female"},
{"id":"3","m_id":1,"value":"Other"}]
Click here
You can do this way also, by using Javascript Filter():
var result = obj1.filter(function(v){
return v.m_id == 1;
});
DEMO
In AngularJS v.1.1.3 exact filter is provided natively
var result = $filter('filter')(obj1,
{m_id : 1},
true // ==========> this is for exact match
);
Working DEMO
Change
var result = $filter('filter')(obj1, {
m_id : "1"
});
to
var result = $filter('filter')(obj1, function(item) { return item && item.m_id == 1; });
Demo here
Related
i am having a json response from which i wanted to create new json object
response = [
{Detail:"Reuters ID",keyName:"Reuters_ID"},
{Detail:"Parity One",keyName:"parity_one"},
{Detail:"Parity level",keyName:"parity_level"}
];
i wanted to achieve this after manipulating keys and value pair
lang_Arr =[
{Reuters_ID:"Reuters ID"},
{parity_one:"Parity One"},
{parity_level:"Parity level"}
];
i have tried doing it in two ways
1) in this getting error as unexpected tokken (.)
var Lang_arr =[];
angular.forEach(response, function(value, key) {
Lang_arr.push({value.keyName:value.Detail});
});
2) here getting unxepected token [
var Lang_arr =[];
angular.forEach(response, function(value, key) {
Lang_arr.push({value['keyName']:value['Detail']});
});
i have tried assigning the values seperatly too but it doesn't work there also
var Lang_arr=[];
var k ='';
var v ='';
var i = 1;
angular.forEach(response, function(value, key) {
k ='';
v ='';
i = 1;
angular.forEach(value,function(val,key){
if(i == 1 )
k = val;
if(i == 2)
v = val;
if(!empty(k) && !empty(v))
Lang_arr.push({k:v})
i++;
});
});
You can use javascript map function to map the objects to array
var response = [
{Detail:"Reuters ID",keyName:"Reuters_ID"},
{Detail:"Parity One",keyName:"parity_one"},
{Detail:"Parity level",keyName:"parity_level"}
];
var lang_Arr =[];
lang_Arr = response.map(function(o){
var obj = {};
obj[o.Detail] = o.keyName;
return obj;
})
console.log(lang_Arr)
With Angular forEach also you can achieve this functionality
var response = [
{Detail:"Reuters ID",keyName:"Reuters_ID"},
{Detail:"Parity One",keyName:"parity_one"},
{Detail:"Parity level",keyName:"parity_level"}
];
var modifiedArray = [];
angular.forEach(response, function(val, key) {
var res = {};
res[val.keyName] = val.Detail;
this.push(res);
}, modifiedArray);
console.log(modifiedArray)
Working Example in Fiddle
You have to assign it in the http call that gets the response
$htpp.get(....).then(function(response){
lang_arr = [];
response.forEach(function(obj){
var item = {obj.keyName : obj.detail};
lang_arr.push(item);
}
I have a teamDetails array, within which is a squad array, within which are player objects. Each player object has an injured property which contains the value "true" or "false".
I want to write a function that loops through the array returning only players whose injured property evaluates to true.
This is what I have so far (not working):
$scope.injuredPlayerSearch = function() {
var injuredPlayers = [];
$scope.teamDetails.squad.forEach(function(o) {
if (o[injured] === true) {
injuredPlayers.push(o)
}
});
return injuredPlayers;
}
I can't see what's wrong with this. If anyone can, would appreciate some help.
You do not need to write any function. angular is there for you.
var injuredPlayers = $filter('filter')($scope.teamDetails.squad, {injured:true}, true);
Here $filter is angular filter. Do dependency inject to your controler or sevice where you are using.
For more about angular filter refer here
Note: 2nd true is for strict type checking. it is equivalent to injured===true
EDIT
For showing it to directly on view angular has much better solution.
{{teamDetails.squad | filter:{injured:true}:true}}
For use in view no need any dependency injection or controller.
If the iteration is within an array of array this is the correct implementation:
$scope.injuredPlayerSearch = function() {
var injuredPlayers = [];
$scope.teamDetails.forEach(function(t){
t.squad.forEach(function(o) {
if (o[injured] === true) {
injuredPlayers.push(o)
}
});
});
return injuredPlayers;
}
You could use filter to return players who are injured:
$scope.injuredPlayerSearch = function() {
return $scope.teamDetails.squad.filter(function(o) {
return o[injured];
});
}
try this
var injuredPlayers = [];
angular.forEach($scope.teamDetails.squad,function(s){
if (s.injured === true) {
injuredPlayers.push(s)
}
})
return injuredPlayers;
Use the javascript filter
var players = [{ id : 0 , injured : true},
{ id : 1 , injured : false},
{ id : 2 , injured : false},
{ id : 3 , injured : true},
{ id : 4 , injured : true}];
var injuredPlayers = players.filter(filterByInjured)
function filterByInjured(player) {
if ('injured' in player && typeof(player.injured) === 'boolean' && player.injured === true) {
return true;
}
}
console.log(injuredPlayers);
You did everything correct just left something
$scope.injuredPlayerSearch = function() {
var injuredPlayers = [];
angular.forEach($scope.teamDetails.squad,function(o) {
if (o[injured] === true) {
injuredPlayers.push(o)
}
});
return injuredPlayers;
}
I'm having difficulty with NgTable, however the functionality I'm looking for may be a limitation on the table framework.
I'm using an API call within the getData, and the data is being grouped (via the groupBy property in the settings param).
I want to be able to use a global filter on the data, I can't seem to get it work with grouping. There's two examples, except they don't mix:
Grouping: http://ng-table.com/#/grouping/demo-grouping-basic
Global filtering: http://ng-table.com/#/filtering/demo-api
Any suggestions?
Table declaration/config
$scope.tableNotesParams = new ngTableParams({
page: 1, // show first page
count: 10, // count per page: use total result set in this case,
sorting: {
created_at: 'desc'
}
}, {
groupBy: function( note ) {
return moment( note.created_at ).format( 'YYYY' );
},
getData: function ( $defer, params ) {
$scope.request.notes.state = 'started';
$scope.request.notes.notesSpinner = true;
var offset = params.count() * ( params.page() - 1 );
// Default
var urlQueryParams = {
'email': member.accounts.email,
'offset': offset,
'limit': params.count() || 10
};
notesApiService.getNotes( urlQueryParams ).then( function ( results ) {
$scope.notes = results.data;
$scope.noteMembers = extractionService.getAllUniqueMembers( $scope.notes );
// Get the range values, expecting value to be: items 1-10/655
var noteHeaders = results.headers();
var notesRangeValues = noteHeaders['content-range'].match( /(\d{1,})/g );
$scope.tableNotesMetaData = {
offsetStart: notesRangeValues[0] || 0,
offsetEnd : notesRangeValues[1] || 0,
totalCount : notesRangeValues[2] || 0
};
// Update parent controller count
$scope.tabs.notes.count = notesRangeValues[2] || 0;
// Update the total
params.total( $scope.tableNotesMetaData.totalCount );
var orderedData = params.sorting() ?
$filter('orderBy')($scope.notes, params.orderBy()) :
$scope.notes;
$defer.resolve( orderedData );
$scope.request.notes.state = 'completed';
$scope.request.notes.notesSpinner = false;
});
}
});
Edit:
The filtering example for a global filter doesn't do anything to the grouped data:
function applyGlobalSearch(){
var term = self.globalSearchTerm;
if (self.isInvertedSearch){
term = "!" + term;
}
self.tableParams.filter({ $: term });
}
I don't think it's performant to query your notesApiService.getNotes() in the getData()-function, but whatever. Since we don't have the HTML or a JSBin to work with, it's mostly guestimate:
notesApiService.getNotes( urlQueryParams ).then( function ( results ) {
var term = $scope.globalSearchTerm.toLowerCase();
if (term.length == 0) {
$scope.notes = angular.copy(results.data, []);
} else if (term.length > 1) {
$scope.notes = results.data.filter(function(item) {
var val = JSON.stringify(item).toLowerCase();
return (val.indexOf(term) != -1);
});
}
I'm working on this codepen. The data comes from an array of objects, and I need to make a filter only by name and amount.
I have this code, but if you type a character in the search box, it only search by amount, and not by name too. In other words, if the you type 'warren' or '37.47' it has to return the same result, but doesn't works.
var filterFilter = $filter('filter');
$scope.filter = {
condition: ""
};
$scope.$watch('filter.condition',function(condition){
$scope.filteredlist = filterFilter($scope.expenses,{name:condition} && {amount:condition});
$scope.setPage();
});
You want to create a custom filter for your app.
directiveApp.filter("myFilter", function () {
return function (input, searchText) {
var filteredList = [];
angular.forEach(input, function (val) {
// Match exact name
if (val.name == searchText) {
filteredList.push(val);
}
// Match exact amount
else if (val.amount == searchText) {
filteredList.push(val);
}
});
input = filteredList;
return input;
};
});
You can write your logic in this filter and now use this filter to filter your list.
Update
You can just implement this filter to your custom filter pagination.
Here is the new version of your code. Codepen
List of updates on your code
Added new filter parameter to your ng-repeat attribute
ng-repeat="expense in filteredlist | pagination: pagination.currentPage : numPerPage : filter.condition"
...
Well, finally (based in the idea of Abhilash P A and reading the docs), I solved my question in this way:
var filterFilter = $filter('filter');
$scope.filter = {
condition: ""
};
$scope.$watch('filter.condition',function(condition){
$scope.filteredlist = filterFilter($scope.expenses,function(value, index, array){
if (value.name.toLowerCase().indexOf(condition.toLowerCase()) >= 0 ) {
return array;
}
else if (value.amount.indexOf(condition) >= 0 ) {
return array;
}
});
$scope.setPage();
});
The final codepen ! (awsome)
I want to use multiple filters in controller
Currently using
$filter('limitTo')($filter('lowercase')($filter('translate')('ACTIVE')), 5)
If we have more filters like this. How can I use multiple filters in controller rather conventional format like this?
You can simply introduce variables:
var limitTo = $filter('limitTo');
var lowercase = $filter('lowercase');
var translate = $filter('translate');
var filteredValue = limitTo(lowercase(translate('ACTIVE')), 5);
Or even
var lowercaseStatus = lowercase(translate('ACTIVE'));
var filteredValue = limitTo(lowercaseStatus, 5);
Another strategy would be to use the same syntax as in the view:
var filteredValue = $scope.$eval('"ACTIVE" | translate | lowercase | limitTo:5');
This is an interesting question. Usually you would do something like that or something like this:
var translatedValue = $filter('translate')('ACTIVE');
var lowercaseValue = $filter('lowercase')(translatedValue);
$scope.finalValue = $filter('limitTo')(lowercaseValue, 5)
I created a service inspired by this answer.
app.service('FilterChain',
['$filter', function($filter) {
var chain = {
value : '',
start : function(value) {
this.value = value;
return this;
},
applyFilter : function(filterName, args) {
args = args || [];
args.unshift(this.value);
this.value = $filter(filterName).apply(undefined, args)
return this;
}
};
return chain;
}]);
Usage is like this
$scope.value = FilterChain.start('Active')
.applyFilter('translate')
.applyFilter('limitTo', [5])
.applyFilter('uppercase')
.value;
You can use the service with other filters and objects such as arrays. See a working example here: JSFiddle