如何在Angularjs多个下拉列表中突出显示所选值

时间:2017-09-19 10:25:17

标签: angularjs

如何在AngularJS的multiple类型的下拉列表中突出显示之前选择的值?

我想在下拉列表中突出显示val: 1, 2。范围变量Fruits包含Id的JSON数组,Nameval包含需要突出显示的Id的集合。

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
    <label>Multiple</label>
    <select ng-model="val" ng-options="x as x.Id for x in Fruits" multiple>
    </select>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.Fruits = [
        {
            Id: 1,
            Name: 'Apple'
        },
        {
            Id: 2,
            Name: 'Mango'
        },
        {
            Id: 3,
            Name: 'Orange'
        }
    ];

    $scope.val = [1,2];
});
</script>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

with:

<select ng-model="val" ng-options="x.Id as x.Name for x in Fruits" multiple>
</select>

应该有效

&#13;
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
    <label>With Name: </label>
    <select ng-model="val" ng-options="x.Id as x.Name for x in Fruits" multiple>
    </select>

    <label>With ID: </label>
    <select ng-model="val" ng-options="x.Id as x.Id for x in Fruits" multiple>
    </select>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.Fruits = [
        {
            Id: 1,
            Name: 'Apple'
        },
        {
            Id: 2,
            Name: 'Mango'
        },
        {
            Id: 3,
            Name: 'Orange'
        }
    ];

    $scope.val = [1,2];
});
</script>

</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个。在select语句中使用track by,如果需要多选选项,则必须在ng-model值而不是单个ID中设置这些对象的数组

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body>

    <div ng-app="myApp" ng-controller="myCtrl">
        <label>Multiple</label>
        <select ng-model="val" ng-options="x as x.Id for x in Fruits track by x.Id" multiple>
        </select>
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
            $scope.Fruits = [{Id: 1,Name: 'Apple'},
                {Id: 2,Name: 'Mango'},
                {Id: 3,Name: 'Orange'}];

            $scope.val = [{Id: 1,Name: 'Apple'},
                {Id: 2,Name: 'Mango'}];
        });
    </script>

</body>

</html>