我正在尝试在Angularjs中实现自定义过滤器。但我没有得到那个问题。未按预期获得输出。这是我的代码:
的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>
答案 0 :(得分:5)
将数字个案更改为字符串值:
case '1' : return 'Male';
case '2' : return 'Female';
因为1 !== "1"
。
console.log('1 !== "1" ::::', 1 !== "1"); // true
答案 1 :(得分:2)
您传递的数字是字符串而不是整数。将开关案例编号更改为字符串
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;
});
&#13;
<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>
&#13;
答案 2 :(得分:1)
将数字个案更改为字符串值:
switch(gender){
case '1' : return 'Male';
case '2' : return 'Female';
default: return 'Male';
}
您应该将其转换为字符串,并且还具有默认结果。