Misael Tovar
Misael Tovar

Reputation: 77

Angular UI mask formatted output UNDEFINED

ok, i am using angular ui mask directive. the filter im using is the one for the hours '99:99'

what i am doing is grabbing the ng-model of the input box, converting it to a string, looping through the string, after the second place i am adding a ":" then returning the string formatted. but when i do that the result returned from the function is correct to an extend.

let say i enter 1212 in the input box, by using the ui mask it will look like this 12:12 on the box. when i call the function it returns this 12:12undefined... can someone help me?

http://jsfiddle.net/edgaramaro/KWMmX/

heres my code: HTML:

<div ng-controller="MyCtrl">
    <input type="text" ui-mask="'99:99'" ng-model="time">{{time}}
    <br>{{convert(time)}}
</div>

JS file:

function MyCtrl($scope) {
    $scope.time = '';

    $scope.convert = function (input) {
        var str = input + '';
        var counter = 0;
        var newStr = '';

        while (counter <= str.length) {
            if (counter === 2) 
               newStr += ':';
            newStr += str[counter];
            counter++;
        }

    return newStr;
}

Upvotes: 1

Views: 2736

Answers (1)

Ben Lesh
Ben Lesh

Reputation: 108501

It issue is in your convert function. You can simplify it a bit with a plain old for loop.

I've updated your fiddle

Also, here's what I did to the code in question:

$scope.convert = function(str){
    if(!str) return;
    var counter = 0,
        newStr = '',
        max = Math.min(str.length, 4);
    for(var i = 0; i < max; i++) {
        if(i === 2) newStr += ':';
        newStr += str[i];
    }        
    return newStr;
}

Upvotes: 1

Related Questions