【问题标题】:Adding a static option to ui-select choices向 ui-select 选项添加静态选项
【发布时间】:2021-03-11 20:39:35
【问题描述】:

在下面的代码中,选项是从数据库中动态添加的。

<ui-select ng-model="model.people">
    <ui-select-match>{{$select.selected.name}}</ui-select-match>
    <ui-select-choices repeat="value.id as value in options | filter: $select.search">
        <div ng-bind-html="value.name | highlight: $select.search"></div>
    </ui-select-choices>
</ui-select>

我的问题是:如何手动将选项“全部”添加到下拉列表中。有什么办法可以做到吗?

【问题讨论】:

    标签: angularjs ui-select


    【解决方案1】:

    从服务器取回数据后,最简单的方法是将其添加到组件/控制器中的options。手动将其作为数组中的第一项推送。

    options.splice(0,0,{id: -1, name: 'all'});
    

    【讨论】:

    • @NamburiAkhil - not working 是什么意思?请调试您的脚本并在此添加的代码行上放置一个断点。被击中了吗? options 变量是否改变?你能看到新添加的数组项吗?一旦你这样做,屏幕上会发生什么?执行此代码后,您是否传递了相同的 options 实例?你确定你不是在做上面的拼接然后用来自服务器的数据覆盖它吗?
    • 它有效。我从服务中获取值,然后添加 dataOpt.splice(0,0,{id: -1, name: 'TODAS'});内部方法询问 object.id 是否为-1。谢谢。
    【解决方案2】:

    您可以在控制器本身的 JSON options 中添加一个 static 对象。

    使用Arrayunshift()方法将一个或多个元素添加到数组的开头,并返回新数组的新长度。

    演示

    var app = angular.module('app', ['ui.select']);
    
    app.controller("myCtrl", function () {
        vm = this;
        vm.values = [{
            'key': 22,
            'value': 'Kevin'
        }, {
            'key': 24,
            'value': 'Fiona'
        }];
        vm.values.unshift({'key': '', 'value': 'Static'});
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-select/0.11.2/select.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-select/0.11.2/select.css" rel="stylesheet"/>
    <div ng-app="app" ng-controller="myCtrl as vm">
        <ui-select tagging ng-model="vm.selected" theme="bootstrap">
            <ui-select-match placeholder="Pick one...">{{$select.selected.value}}</ui-select-match>
            <ui-select-choices repeat="val in vm.values | filter: $select.search track by val.value">
                <div ng-bind="val.value | highlight: $select.search"></div>
            </ui-select-choices>
            
        </ui-select>
    </div>

    【讨论】:

      【解决方案3】:

      这应该可行:

      <ui-select ng-model="model.people" theme="bootstrap">
      <ui-select-match>{{ $select.selected }}</ui-select-match>
      <ui-select-choices repeat="choice in ['option 1', 'option 2']">
          <span>{{ choice }}</span>
      </ui-select-choices>
      

      【讨论】:

        【解决方案4】:

        如果您想保持options 列表不变,并且只在下拉列表中添加静态选项,这将起作用:

        <ui-select-choices repeat="value.id as value in [ staticOption ].concat(options)">
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多