Próbuję napisać mój pierwszy niestandardowy filtr dla AngularJS. Chcę mieć możliwość określenia, czy coś jest ciągiem lub liczbą. Jeśli jest to liczba, formatuje ją jako taką z wbudowanym filtrem | number
.Niestandardowy filtr AngularJS dla tekstu/numeru
Obecnie have a workaround using ng-if
:
HTML
<table>
<tr ng-repeat="(key, val) in data">
<td>{{key}}</td>
<td ng-if="isNumber(val)">{{val | number}}</td>
<td ng-if="!isNumber(val)">{{val}}</td>
</tr>
</table>
Kontroler:
$scope.data = {
One:55689,
two:"consider all the options",
three:800243,
four:"all over",
five:"or just beginning"
};
$scope.isNumber = function (value) {
return angular.isNumber(value);
};
Pomyślałem, że byłoby to lepsze rozwiązanie, aby przypisać go jako swój własny filtr chociaż. To jest to, co mam do tej pory (tak, wiem, że to tylko kości ... to mój pierwszy).
.filter('textOrNumber',function(){
return function (input) {
if(typeof input === 'number'){
console.log("I'm a number");
//return as formatted number
} else {
console.log("Not a number");
//do nothing, just return
};
return input;
};
})
Kiedy sprawdza się numer, mogę tylko mieć ona zastosowanie kątowego | number
filtr? Czy muszę ręcznie samodzielnie wykonać filtr w javascript?
To jest dokładnie poprawne. Wiedziałem, że to może być tak proste, jak to. Nie patrzyłem na '$ filter'. Będę musiał to zrobić, aby lepiej zrozumieć, do czego jest zdolny. – EnigmaRM