search

Home  >  Q&A  >  body text

Why my ng-options bound value doesn't work - Stack Overflow

$scope.selected=0;

<select class="form-control lls-input-lg" id="cooperationPlatform" ng-model="selected">
    <option value="0">全部</option>
    <option ng-repeat="o in keyArr"
          value="{{o.id}}">
        {{o.prodName}}
     </option>
</select>

It comes out like this

And it is not selected by default

Another point is that if I use ng-options, it will look like this

The value is very strange. In my data, id: 1, like this, there is an additional label

Please answer! !

PHPzPHPz2783 days ago1074

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-05-15 17:15:54

    You need to use ng-value for value binding. It is also recommended to add the default options to the array and perform them uniformly ng-repeat 循环就好了。同时建议命名规范一下哈如:user in usersproduce in produces in this form.

    ng-options example

    <select class="form-control lls-input-lg" id="cooperationPlatform"
       ng-options="o.prodName for o in keyArr"
       ng-model="selected">
    </select>
    
    ----------
    
    $scope.selected=$scope.keyArr[1];

    ng-value example

    <!DOCTYPE html>
    <html lang="en" ng-app="myapp">
    <head>
        <meta charset="UTF-8">
        <title>Angular Repeat-Done Demo</title>
        <script src="https://cdn.bootcss.com/angular.js/1.6.3/angular.min.js"></script>
    </head>
    <body ng-app="myapp">
    <p ng-controller="AppCtrl">
        <h4>Users List</h4>
        <select class="form-control lls-input-lg" id="cooperationPlatform" ng-model="selected">
            <option ng-repeat="o in keyArr"
                    ng-value="{{o.id}}">
                {{o.prodName}}
            </option>
        </select>
    </p>
    <script type="text/javascript">
        var myapp = angular.module("myapp", [])
                .controller("AppCtrl", ['$scope', function ($scope) {
                    $scope.selected=2;
                    $scope.keyArr = [
                        {
                            id: 0,
                            prodName: '全部'
                        },
                        {
                            id: 1,
                            prodName: '天金所'
                        },
                        {
                            id: 2,
                            prodName: '测试'
                        },
                        {
                            id: 3,
                            prodName: '还是测试'
                        }
                    ]
                }])
    </script>
    </body>
    </html>

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-15 17:15:54

    https://docs.angularjs.org/ap...

    reply
    0
  • Cancelreply