kyserslick kyserslick - 6 days ago 5
AngularJS Question

Set default value on selected ng-model and manage ng-change

I cannot set the default value for my selected Item knowing that I'm supposed to get the default value from a json () use that selected value to show another form.

In my controller I have set the selected this way:

.controller('attributeFacetCtrl', function ($scope, tabsService, $location, contentService, attribute) {

$scope.attribute = attribute;

$scope.types = [{
val: 'terms'
}, {
val: 'continuous'
}];

$scope.selected = $scope.attribute.facet.data.type;

$scope.isTerms = false;

$scope.validateFrom = function() {

var chk = $scope.selected.val;

if (chk === 'terms') {
$scope.isTerms = true;
} else {
$scope.isTerms = false;
}
};
})


the result of $scope.attribute.facet.data.type="terms"

And in my view I have this

<div class="form-group">
<label class="wk-field-label">
<i class="icon-asterisk wk-prefield wk-mandatory"></i>
Type
</span>
</label>
<select class="wk-field-input" ng-model="selected"
ng-options="typeValue as typeValue.val for typeValue in types"
ng-change="validateFrom()"
required></select>
</div>
<div ng-if="isTerms" ng-repeat="orders in attribute.facet.data.order">
<div>
<label class="wk-field-label">
<i class="icon-asterisk wk-prefield wk-mandatory"></i>
Order
</span>
</label>
</div>
</div>

Lex Lex
Answer

The problem is that you're setting $scope.selected to a string ("terms"), but when you're loading up ng-options it's loading it with objects that have a val property.

If you don't necessarily need $scope.selected to be an object, then you can change your ng-options to the following:

ng-options = "typeValue.val as typeValue.val for typeValue in types"

If you require $scope.selected to be an object with a val property then you will need to set its initial value appropriately and not set it to a string in order to set the default selection.