Saturday, 15 March 2014

angularjs custom filter on ng-class -



angularjs custom filter on ng-class -

hello want create simple search table of data. want highlight if info matched user type input. done doc below since i'm starting using angular wonder there improve way? custom filter maybe ?

<!doctype html> <!-- alter license header, take license headers in project properties. alter template file, take tools | templates , open template in editor. --> <html ng-app="myapp"> <head> <title>todo supply title</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script> <style type="text/css"> table td{ padding: 5px; } .true{ color: green; background-color: blue; } </style> </head> <body> <div ng-controller="filtrcontroller"> <div>{{search}}<hr/></div> <input type="text" ng-model="search"/> <table> <thead> <tr> <td>name:</td> <td>param1:</td> <td>param2:</td> </tr> </thead> <tbody> <tr ng-repeat="foo in info | filter:search"> <!--<td ng-class="{true:'true',false:''}[search === foo.name]">{{foo.name}}</td>--> <td ng-class="customfilter(search,foo.name)">{{foo.name}}</td> <td ng-class="customfilter(search,foo.param1)">{{foo.param1}}</td> <td ng-class="customfilter(search,foo.param2)">{{foo.param2}}</td> </tr> </tbody> </table> </div> <script type="text/javascript"> var myapp = angular.module('myapp',[]); myapp.controller('filtrcontroller',function ($scope) { $scope.customfilter = function(search,searchto) { if(search != '') { if(searchto.indexof(search) > -1) homecoming 'true'; homecoming ''; } }; $scope.data = [ { name:'name foo1', param1:'param of foo1', param2:'param 2 of foo1' }, { name:'name foo2', param1:'param of foo2', param2:'param 2 of foo2' }, { name:'name sfoo3', param1:'param of foo3', param2:'param 2 of foo3' }, ] }); </script> </body>

you need custom filter this:

$scope.customfilter = function(data, searchfor) { if (angular.isundefined(data) || angular.isundefined(searchfor)) homecoming data; angular.foreach(data, function(item) { if(angular.equals(item, searchfor)) item.highlighted = true; }); homecoming data; }

and html this

<tr ng-repeat="foo in info | customfilter:{something:1}" ng-class="{highlighted: foo.highlighted}">

update:

so, need explain approach in more details. have info of needed highlighted. need set new property in info , highlight (using css , ng-class) if property set true. setting property can create custom filter takes info array, changes internal state setting property , homecoming array result. implemented you.

update#2

same behaviour ng-filter needed. here is.

angularjs ng-class

No comments:

Post a Comment