[英]How to use $filter with select in angular.js
如何根據用戶選擇的值在不同的濾鏡之間切換? 我有三個過濾器(“ largeNumber”,“ Percentage”,“ Bytes”),我想根據用戶選擇的值在這些過濾器之間切換。 現在,我正在使用我的js代碼中的過濾器,請參見小提琴,但是它無法按預期的效果運行:
預期產量
當用戶鍵入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標簽而不應用過濾器,它將僅顯示在輸入字段中輸入的值。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.