1

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.

2 Answers 2

5

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}}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help. Could you explain your usage of 'value' throughout the template and controller? I'm confused
In controller version, $scope.value is the model behind yout input field. In ng-change, i call a function and pass this model in parameters, so i can use it directly (not by using the scope) in my function
4

$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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.