I'm trying to implement custom filter in Angularjs. But I'm not getting what is the problem in that. Not getting the output as expected. Here is my code:
script.js
var myApp = angular.module('myModule', []);
myApp.filter("gender", function(){
return function(gender){
switch(gender){
case 1 : return 'Male';
case 2 : return 'Female';
}
}
});
myApp.controller('myController', function($scope){
var employees = [
{ name : 'Raghu', gender : '1', salary : 84000.779 },
{ name : 'Anil', gender : '1', salary : 78000 },
{ name : 'Ramya', gender : '2', salary : 118000 },
{ name : 'Shwetha', gender : '2', salary : 68000 },
{ name : 'Chethan', gender : '1', salary : 168000 }
];
$scope.employees = employees;
});
page.html
<div class="container" ng-controller="myController">
<h1>Angular Example Ten</h1>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Gender</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees">
<td>{{ employee.name }}</td>
<td>{{ employee.gender | gender }}</td>
<td>{{ employee.salary }}</td>
</tr>
</tbody>
</table>
</div>
Change the numeric cases to string values :
case '1' : return 'Male';
case '2' : return 'Female';
Because 1 !== "1"
.
console.log('1 !== "1" ::::', 1 !== "1"); // true
</div>
Change the numeric cases to string values :
switch(gender){
case '1' : return 'Male';
case '2' : return 'Female';
default: return 'Male';
}
You should convert that to string and also have the default result.
the number you are passing is string not an integer. change the switch case numbers to string
switch(gender){
case "1" : return 'Male';
case "2" : return 'Female';
}
var myApp = angular.module('myModule', []);
myApp.filter("gender", function(){
return function(gender){
debugger
switch(gender){
case "1" : return 'Male';
case "2" : return 'Female';
}
}
});
myApp.controller('myController', function($scope){
var employees = [
{ name : 'Raghu', gender : '1', salary : 84000.779 },
{ name : 'Anil', gender : '1', salary : 78000 },
{ name : 'Ramya', gender : '2', salary : 118000 },
{ name : 'Shwetha', gender : '2', salary : 68000 },
{ name : 'Chethan', gender : '1', salary : 168000 }
];
$scope.employees = employees;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="myModule" ng-controller="myController">
<h1>Angular Example Ten</h1>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Gender</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees">
<td>{{ employee.name }}</td>
<td>{{ employee.gender | gender }}</td>
<td>{{ employee.salary }}</td>
</tr>
</tbody>
</table>
</div>
</div>