如何使用$ filter和angular.js中的select
问题描述:
如何根据用户选择的值在不同的过滤器之间切换?我有三个过滤器('largeNumber','Percentage','Bytes'),我想根据用户选择的值在这些过滤器之间切换。现在我使用的过滤器从我的js代码见小提琴然而由于预期jsfiddle:
预期输出
选择了1200的用户类型,当大数它不工作==>1K
视图
<div ng-controller="MyCtrl">
<form role="form" class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="sample" ng-model="numberData" placeholder="Enter Number">
<select class="form-control inline" id="format" ng-model="numberType"
ng-options='type for type in selectType' ng-change="selected()">
<option style="display:none" value="" class='formOptions'>select a type</option>
</select>
</div>
</form>
<h1> data here: {{numberData}}</h1>
</div>
的jsç颂:
var myApp = angular.module('myApp',[]);
myApp.filter('largeNumber', function(){
return function(number, decPlaces) {
var orig = number;
var dec = decPlaces;
// 2 decimal places => 100, 3 => 1000, etc
decPlaces = Math.pow(10, decPlaces);
// Enumerate number abbreviations
var abbrev = ["k", "m", "b", "t"];
// Go through the array backwards, so we do the largest first
for (var i = abbrev.length - 1; i >= 0; i--) {
// Convert array index to "1000", "1000000", etc
var size = Math.pow(10, (i + 1) * 3);
// If the number is bigger or equal do the abbreviation
if(size <= Math.abs(Math.round(number))) {
// Here, we multiply by decPlaces, round, and then divide by decPlaces.
// This gives us nice rounding to a particular decimal place.
var number = Math.round(number * decPlaces/size)/decPlaces;
// Handle special case where we round up to the next abbreviation
if((number == 1000) && (i < abbrev.length - 1)) {
number = 1;
i++;
}
// console.log(number);
// Add the letter for the abbreviation
number += abbrev[i];
// We are done... stop
break;
}
}
return number;
}
})
function MyCtrl($scope, $filter) {
$scope.selectType = ['Large Number', 'Percentage', 'Bytes']
$scope.selected = function() {
console.log($scope.numberType)
return $scope.numberType
};
$scope.selectedType = $scope.selected()
$scope.sendSelectedItem = function(){
if($scope.selectedType == "Large Number"){
return $filter('largeNumber')(0)
}
}
}
答
HTML变化:
<h1> data here: {{numberDataFormatted}} </h1>
脚本更改:下面的代码是你的控制器需要。
$scope.selectType = ['Large Number', 'Percentage', 'Bytes'];
$scope.sendSelectedItem = function() {
if ($scope.numberType == "Large Number") {
return $filter('largeNumber')($scope.numberData, 0);
}
// Handle other types or defaults here
}
$scope.selected = function() {
$scope.numberDataFormatted = $scope.sendSelectedItem();
};
// Set the initial type
$scope.numberType = "Large Number";
与您的代码的问题:
$ scope.sendSelectedItem定义,但不被调用。当选择一个项目并选择时,应该调用 ,您可以应用所需的过滤器并将结果分配给另一个范围模型变量。
$ scope.numberData是一个未格式化的值。如果将其分配给h1标签而不应用过滤器,则只会显示输入字段中输入的值。
希望这会有所帮助。
发生了什么,我错过了这里的一点...当用户类型1200应该下拉显示largeNumbers? – Thalaivar
如果用户输入1200并从下拉列表中选择大数字,那么过滤器应该适用 – Imo
它应该在哪里应用......我的意思是在一个新的div区域? – Thalaivar