AngularJS Filter inside controller – angular custom filter example

AngularJS Filter inside controller – angular custom filter example

Using AngularJS Filter Inside the Controller Example

JSON – Data
[php]
{“response”:”success”,”data”:[{“userid”:”385″,”usercode”:”FSP5443″,”user_title”:”infinityknow I\u00a0″},{“userid”
:”386″,”usercode”:”FSP5444″,”user_title”:”infinityknow I, muntlig\u00a0″},{“userid”:”387″,”usercode”:”FSP5446″
,”user_title”:”infinityknow II\u00a0″},{“userid”:”388″,”usercode”:”FSP5451″,”user_title”:”infinityknow II, muntlig
\u00a0″},{“userid”:”829″,”usercode”:”PSP5297″,”user_title”:”infinityknow niv\statuscode II\u00a0″},{“userid”:”830″
,”usercode”:”PSP5298″,”user_title”:”infinityknow niv\statuscode II, muntlig\u00a0″},{“userid”:”831″,”usercode”:”PSP5299″
,”user_title”:”infinityknow niv\statuscode III\u00a0″},{“userid”:”832″,”usercode”:”PSP5300″,”user_title”:”infinityknow
niv\statuscode III, muntlig\u00a0″}]}
[/php]

script.js
[php]
myapp.directive(‘autocomplete’, function($filter) {

return {
restrict: ‘A’,
link: function (scope, elem, attrs) {
elem.autocomplete({
source: function (request, response) {
var params = request.term;
var data = scope.dataSource;
if (data) {
var result = $filter(‘filter’)(data,params);
//console.log(result);
angular.forEach(result, function (item) {
item[‘value’] = item[‘user_title’] + ” [“+ item[‘usercode’]+”]”;
//item[‘value’] = item[‘user_title’];
});
}
response(result);

READ :  Angular ng-repeat reverse Example - reverse filter

},
minLength: 1,
select: function (event, selectedItem) {
scope.valgkeywords= selectedItem.item.value;
scope.$apply();
event.preventDefault();
}
});
}

};

});
[/php]

AngularJS – $filter inside controller Examples

Filters format all tthe value of your an expression for display data to the user friendly.and
They can be used in simple HTMLview templates, and angularjs controllers or services.

Using filters in controllers, services, and directives

[php]
angular.module(‘FilterInControllerModule’, []).
controller(‘FilterController’, [‘filterFilter’, function FilterController(filterFilter) {
this.array = [
{name: ‘infinityknow’},
{name: ‘tutorial’},
{name: ‘satus’},
{name: ‘word’},
{name: ‘angular’},
{name: ‘vuejs’}
];
this.filteredArray = filterFilter(this.array, ‘a’);
}]);

[/php]

Building Custom AngularJS Filters

To declare a simple filter we pass in two same parameters to app.filter

[php]
app.filter(‘myFilter’, function() {
return function(input, optional1, optional2) {
var result;
// Do filter here some work here
return result;
}

READ :  JavaScript Read XML File local Example

});
[/php]

ifEmpty Filter using AngularJS Example

[php]
angular.module(‘liveapp’).filter(‘ifEmpty’, function() {
return function(input, defaultValue) {
if(isNaN(input))
{
return 0;
}

return input;
}
});
[/php]

Example

Leave a Comment