Martijn
Martijn

Reputation: 24789

How to create $modelValue when it is undefined in Angular?

I am busy creating a time input box directive. The HTML looks like this:

<time-input data-ng-model="model.Time"></time-input>

It is possible that model.Time is null. This means also off course that $modelValue of the ngModelController is undefined. But when I want to create / set the $modelValue, it is set back to undefined and I don't know why.

Here is a Fiddle where you can see my problem in action. As you can see time 1 is working, but time 2 is not. As soon as you enter a valid value for time 2, it is removed.

Can someone explain why this is and how to solve this?

Upvotes: 0

Views: 1104

Answers (1)

Fedor Skrynnikov
Fedor Skrynnikov

Reputation: 5609

You don't need to put model by hands...it automatically put there a value you return from parser as well as view has the value that formatter returns

works here

So your parser looks like this and updateTimeInModel returns object for model:

controller.$parsers.unshift(function (value) {
   if (!value) return;
     var valid = regEx.test(value);

     controller.$setValidity('validTime', valid);

     if (valid) {
       return updateTimeInModel();
     }

     console.log(controller.$modelValue);
     return null;

 })

Upvotes: 2

Related Questions