2

How do I set a default value on an angularjs model? I'm looking for something like this if it's possible:

div.form-multiple(ng-model='story.r || []', form-multiple="form-multiple")

Right now story.r is just undefined. I would like to prefill it.

Here's my directive. The odd thing here is that it works just fine if $modelValue already has an array but does not if it's just undefined.

.directive('formMultiple', function() {
  return {
    require: '?ngModel',
    link: function(scope, elm, attr, ngModel) {
      if (!ngModel)
        return

      function pushIntoArray () {
        if(ngModel.$modelValue && elm.find('input:last').val() != '') { // this works fine
          ngModel.$modelValue.push(scope.formMultipleDefault)
          scope.$digest()
        }
        else if (!ngModel.$modelValue) { 
          ngModel.$modelValue = [scope.formMultipleDefault] // this block does nothing
          console.log(ngModel) // returns $modelValue undefined.
        }
      }


      pushIntoArray()
      elm.on('blur', 'input', function() {
        pushIntoArray()
      });

    }
  };
})

1 Answer 1

1

Since you are using a directive, what you're looking for is:

ngModel.$setViewValue('something');

in the link function.

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

5 Comments

Thanks but I would like to know how to set an arbitrary default for ng-model.
Do you mean sth like: ng-init='story.r=1'
@Harry do you mind explaining what you mean by that, if it's not exactly what I gave in my answer?
Sorry for the unclear comment. I think setting it in the controller is unmaintainable. I would rather set it in the directive or the html.
It is the way to do it. Since you are using a directive, controller = directive in my post, but I was not aware of that before your edit. I will give you a more concrete solution now.

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.