2

Here is my JSFiddle. And here is the code:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-init="my_number=255">
    Convert a number to hexadecimal, using a custom made service inside a custom made filter:

    <input ng-model="my_number">
    <h1>{{my_number | myFormat}}</h1>

</div>
<script>
    var app = angular.module('myApp', []);
    app.service('hexafy', function() {
        this.myFunc = function(x) {
            return x.toString(16);
        }
    });
    app.filter('myFormat', ['hexafy', function(hexafy) {
        return function(x) {
            return hexafy.myFunc(x);
        };
    }]);

</script>

The filter seems to work just fine on the intialized value (255 shows as ff), but when that value is changed by the user, the filter doesn't work anymore (for instance, 254 shows as 254, not the expected 'fe')

How can I fix this? Also, I'm new to Angular, and this is the first time I've used JSFiddle. I don't know how to reference the code file/s in the JS window from HTML. That's why I've put the code within script tags. How would I reference the code through src if it were in the JS window instead?

I should add that the code is mostly from an example from the w2schools AngularJS tutorial. I've modified if to work with user input (unsuccessfully so far).

2 Answers 2

2

put either input type as number or use parseInt like [hexafy.myFunc(parseInt(x));].

Sign up to request clarification or add additional context in comments.

1 Comment

Great! setting the type attribute to "number" worked just fine. However, I have not figured out where in my JS code I'd need to use the parseInt function. Have tried in the filter as well as the service. Neither worked. Also, any help with the second question (using the JS pane for code and referencing it) would be appreciated.
0

This is because after the user input, the value isn't a number anymore but a string. You can change it to this:

<input ng-model="my_number" type="number" />

See jsfiddle

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.