• 技术文章 >Web开发 >JavaScript

    angularjs ng-options设置多个默认选项

    宋雪维宋雪维2021-01-14 19:50:26原创1453

    ng-options可以接收一个数组或者对象,并对它们进行循环,将内部的内容提供给select标签内部的选项。而select中需要设置默认值,是如何设置呢?其实可以使用ng-model绑定数据myColor,也可以在对应的controller中定义ng-model全局数据$scope.myColor,并为其赋值。或者双向绑定指定ng-model,设置选中的值。

    ng-options的表达式格式:

    <所选属性> as <标签> for <变量> in <数组>

    方法一:使用ng-model绑定数据myColor。

    angular.module('myApp', [])
      .controller('MyController', ['$scope'], function($scope) {
        $scope.colors = ['black', 'white', 'red', 'blue', 'yellow'];
        
        $scope.myColor = $scope.colors[2];
      })

    方法二:在对应的controller中定义ng-model全局数据$scope.myColor,并为其赋值。

    <div ng-controller="MyController">
      <select ng-model="myColor" ng-options="color for color in colors"></select>
    </div>

    注意:赋值为select的默认值。

    方法三:双向绑定指定ng-model,设置选中的值。

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml" ng-app="app">
    <head>
        <title>select</title>
        <script src="JS/angular.min.js"></script>
        <script>
            var app = angular.module('app', []);
            app.controller('selectController', function ($scope) {
                $scope.mycity = '北京';
                $scope.Cities = [{ id: 1, name: '北京', group: '中国' }, { id: 2, name: '上海', group: '中国' }, { id: 3, name: '广州', group: '中国' }];
            });
        </script>
    </head>
    <body>
        <div ng-controller="selectController">
            <select ng-model="mycity" ng-options="city.name as city.name group by city.group for city in Cities"></select>
            <h1>欢迎来到{{mycity}}</h1>
        </div>
    </body>
    </html>

    以上就是小编总结的的三种angularjs ng-options设置默认值额方法,希望能对你有所帮助哦~

    专题推荐:angularjs ng-options
    品易云
    上一篇:json解析速度 下一篇:json解析失败是什么意思

    相关文章推荐

    • 如何使用python pillow库?• python中Mako库怎么用?• Python的scikit-image模块是什么?• Python的信号库Blinker有何用法?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网