简体   繁体   中英

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

在此处输入图片说明

what I need is

在此处输入图片说明

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

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 }
  ];

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM