Issue
What I would like to create is a filter which will pull the numbers out of text that is put in a text box. For example:
User types: The cat went to 4 stores and bought 3 bags of cat litter for 1 dollar.
Result would be: [4, 3, 1]
The filter will see because of a previous filter ['the', 'cat', 'went', 'to', '4' ...]
So what I tried to create was a for loop that would go through the array and check each item to see if it is in fact a number. However, the for loop breaks the app when it isn't commented out. Any help is appreciated.
filter('showNum', function() {
// this filter is not complete but it will return only numbers from an array
return function isNumeric(title){
var numbers, i, len, numberToAdd;
numbers = [];
len = title.length;
// for(i=0; i<len; i+=1){
// numberToAdd = title[i];
// if(!isNAN(numberToAdd)===False); {numbers.push(numberToAdd);}
return numbers;
};
})
Solution
I would change the filter to something like this:
javascript
.filter('showNum', function() {
return function(input) {
if (!input)
{
return [];
}
return input
.split(' ')
.filter(function(item){
return item && !isNaN(item);
})
.map(function(item){
return parseInt(item);
})
};
});
html
<body ng-controller="MainCtrl">
<input type="text" ng-model="input">
<p>result: {{ input | showNum }}</p>
</body>

http://plnkr.co/edit/Hp91dIXbThzvnwzIFbVn?p=preview
Answered By - Jossef Harush Kadouri
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.