CaffeineShots
CaffeineShots

Reputation: 2162

Angular ng-init for selected option is not working

I'm working on this fidde HERE

this is my controller:

angular.module('demoApp', []).controller('DemoController', function($scope) {

  $scope.options = [
    { label: 'one', value: '1' },
    { label: 'two', value: '2' },
    { label: 'three', value: '3' },
    { label: 'four', value: '4' }
  ];

    $scope.selected = {
        "aaa": [
            {
                "bbb": {
                    "ccc": 1
                }
            },
            {
                "bbb": {
                    "ccc": 2
                }
            },
            {
                "bbb": {
                    "ccc": 3
                }
            },
         ]
    }

});

the $scope.options is the option for my select dom and the $scope.selected is the selected item in my select dom

this is my index.html :

<body ng-app="demoApp">
    <div ng-controller="DemoController">
        <div ng-repeat="data in selected.aaa">
            <select ng-model="data.bbb.ccc"
                ng-options="opt.value as opt.label for opt in options" ng-init="data.bbb.ccc = data.bbb.ccc || options[$index].value">
            </select>
            selected must be : {{data.bbb.ccc}}
        </div>
    </div>
</body>

what I have is

enter image description here

what I need is

enter image description here

the tree structure of $scope.selected is expected, it is the real structure I need to deal with. Could anyone help me?

Upvotes: 0

Views: 1422

Answers (1)

Harry Burns
Harry Burns

Reputation: 890

Everything is simple. Your options contains strings, but your tree structure contains int values. You need to change your options object:

  $scope.options = [
    { label: 'one', value: 1 },
    { label: 'two', value: 2 },
    { label: 'three', value: 3 },
    { label: 'four', value: 4 }
  ];

Upvotes: 2

Related Questions