Reputation: 95
I want to make a Roman numeral calculator that converts numbers, typed in a text input, to the numerals instantly. I understand how to bind a variable to the text input but I don't know how to 'perform a function' on it as it's being typed. How do I do this?
Thanks.
Upvotes: 1
Views: 7562
Reputation: 1378
Use the ng-change directive : here the docs
Example
In template
<input type="text" ng-change="yourFunction(value)" ng-model="value"/>
In controller
$scope.value = ""
$scope.yourFunction = function(value){
//Put code logic here
}
EDIT :
In your case, you can also create a filter
module.filter("convertToRomanNumber", function(){
//Improve code logic here
return function(input){
var value="";
for(var i=0; i<input; i++){
value+="I"
}
return value;
}
})
and call it in your template
<input type="text" ng-change="yourFunction(value)" ng-model="value"/>
{{value | convertToRomanNumber}}
Upvotes: 5
Reputation: 926
$scope.watch on the ng-model of the text input. Then run the code you want to execute on the ng-model variable.
e.g.
// html...
<input type=text ng-model="textBox" />
// controller
$scope.$watch('$scope.textBox', function(newValue, oldValue) {
// do stuff to the text everytime it changes
});
The benefit of this $scope.$watch is for example you don't want to execute the function on the newValue unless it is 2 or 3 characters more. It just gives you some more control over the function compared to a simple ng-change.
Upvotes: 4