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()
});
}
};
})
Since you are using a directive, what you're looking for is:
ngModel.$setViewValue('something');
in the link function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.