Customize ng-options selection look

妖精的绣舞 提交于 2019-12-09 03:13:36

问题


I'm using a ng-options for a select dropdown menu. I would like to use different color for an option depending on a condition:

select(ng-model='myCompany', ng-options='company.code as company.name for company in companies' **if company.active -> text-color=green**)

Is it possible to do that?

Edit (my jade code):

 form(role='form', name='addForm', novalidate, rc-submit="add()")
    .form-group
        div.row
            div.col-xs-12.col-md-3
                select.form-control(ng-model='form.contract', ng-options='contract as contract.number for contract in contracts', options-class="{true:'active',false:'inactive'}[active]")

回答1:


If you only need to bind the select to string values (not object), you can easily achieve what you want by using ngRepeated <option> elements (instead of ngOptions):

<select ng-model="color">
    <option value="">--- Select a color ---</option>
    <option value="{{c}}" style="background-color:{{c}}" ng-repeat="c in colors">
        {{c}}
    </option>
</select>

If you are in for a little custom directive, you can implement it like this:

app.directive('optionClassExpr', function ($compile, $parse) {
    var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;

    return {
        restrict: 'A',
        link: function optionClassExprPostLink(scope, elem, attrs) {
            var optionsExp = attrs.ngOptions;
            if (!optionsExp) return;

            var match = optionsExp.match(NG_OPTIONS_REGEXP);
            if (!match) return;

            var values = match[7];
            var classExpr = $parse(attrs.optionClassExpr);

            scope.$watchCollection(function () {
                return elem.children();
            }, function (newValue) {
                angular.forEach(newValue, function (child) {
                    var child = angular.element(child);
                    var val   = child.val();
                    if (val) {
                        child.attr('ng-class', values + '[' + val + '].' +
                                               attrs.optionClassExpr);
                        $compile(child)(scope);
                    }
                });
            });
        }
    };
});

And use it like this:

<select ng-model="someObj" ng-options="obj as obj.color for obj in objects"
        option-class-expr="color">
</select>

See, also, this updated short demo.




回答2:


Define your CSS classes:

.green {
    background-color: green;   
}

.blue {
    background-color: blue;
}

and use a function as an angular expression:

$scope.getCompanyClass = function(company)
{
   return company.active ? "green" : "blue";
}

and in your html:

<select>
    <option data-ng-repeat="company in companies" data-ng-class='getCompanyClass(company)'>...</option>
</select>

and the working example as jsfiddle




回答3:


There is a neat solution for the special case that you want to show disabled options in a certain color. You can use disable when:

ng-options='c.code as c.name disable when !c.active for c in companies'

You can then use CSS to match on the disabled attribute and style the respective options the way you like.




回答4:


Please see here http://jsbin.com/wahak/2/edit?html,css,console,output you can do that using css

CSS:

select { color: red; }
option:not(:checked) { color: black; }



回答5:


This is how I am colouring the ng-options. I am using my own example.

var app = angular.module("app", []);
app.controller("homeController", [homeController]);

function homeController() {
    var vm = this;
    vm.differentOptions = [
        { name: "External Visitors", color: "Red" },
        { name: "Internal Visitors", color: "Green" },
        { name: "Other Visitors", color: "Gray" },
        { name: "Extrateresstrial Visitors", color: "Yellow" }
    ];
}

angular.module("app").directive("colorTheOptions", colorTheOptions);
function colorTheOptions($timeout) {
    return {
        link: function (scope, element) {
            $timeout(function () {
                var options = $("option", element);
                options.each(function (index, eachOption) {
                    $eachOption = $(eachOption);
                    var optionText = $eachOption.text();
                    if (optionText) {
                        for (var i = 0; i < scope.vm.differentOptions.length; i++) {
                            var eachAngularOption = scope.vm.differentOptions[i];
                            if (eachAngularOption.name === optionText) {
                                $eachOption.addClass(eachAngularOption.color);
                            }
                        }
                    }
                });
            });
        }
    }
}
.Red {
    color: red;
}

.Green {
    color: green;
}

.Gray {
    color: gray;
}

.Yellow {
    color: yellow;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container" ng-app="app">
    <div class="row" ng-controller="homeController as vm">
        <select class="form-control" color-the-options
                ng-options="option.name for option in vm.differentOptions"
                ng-model="vm.selectedOption"></select>
    </div>
</div>


来源:https://stackoverflow.com/questions/24631325/customize-ng-options-selection-look

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!