2013-06-30 53 views
2

如何在angularjs模型上設置默認值?我在尋找這樣的事情,如果有可能:angularjs ng-model設置默認值

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

現在story.r就是不確定的。我想預先填好它。

這是我的指令。這裏的奇怪之處在於,如果$ modelValue已經有一個數組,但是它沒有定義,那麼它工作得很好。

.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

由於您使用的指令,你要找的是什麼:

ngModel.$setViewValue('something'); 
在鏈接功能

+0

謝謝,但我想知道如何爲ng模型設置一個任意的默認值。 – Harry

+0

你的意思是...... ng-init ='story.r = 1' –

+0

@哈利你介意解釋一下你的意思嗎,如果這不正是我在回答中給出的內容? – finishingmove