ng-repeat 与ng-switch的简单应用

效果如下图所示:

ng-repeat 与ng-switch的简单应用

使用表格显示用户信息,当点击某条用户信息时,在其下方展开一行进行展示。

index.html

<!DOCTYPE html>



<html ng-app="myApp">

    <head>

        <title>TODO supply a title</title>

        <meta charset="UTF-8">

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="../css/uikit.css"/>

        <link rel="stylesheet" href="../css/my-uikit.css"/>

    </head>

    <body>

        

        <div class="uk-panel" ng-controller="UserCtrl">

            <table class="uk-table uk-table-hover uk-table-striped">

                <thead class="uk-bg-primary">

                    <tr>

                        <th>Name</th>

                        <th>Email</th>

                    </tr>

                </thead>

                <tbody ng-repeat="user in users" ng-click="selectUser(user)" 

                       ng-switch on="isSelected(user)">

                    <tr>

                        <td>{{user.name}}</td>

                        <td>{{user.email}}</td>

                    </tr>

                    <tr ng-switch-when="true">

                        <td colspan="2" class="uk-bg-success">{{user.desc}}</td>

                    </tr>

                </tbody>

            </table>

        </div>

        

    </body>

    

    <script src="../js/angular.js"></script>

    <script src="index.js"></script>

</html>

index.js

var myApp = angular.module('myApp', []);



myApp.controller('UserCtrl', ['$scope', function($scope){

        $scope.users = [

            {

                name:'张三',

                email:'[email protected]',

                desc: '张三的详细信息...'

            },

            {

                name:'李四',

                email:'[email protected]',

                desc: '李四的详细信息...'

            },

            {

                name:'王五',

                email:'[email protected]',

                desc: '王五的详细信息...'

            }

        ];

        

        $scope.selectUser = function(user){

            $scope.selectedUser = user;

        };

        

        $scope.isSelected = function(user){

            return $scope.selectedUser === user;

        };

}]);

:ng-repeat指令用于渲染集合元素,并持续监视数据源的变化,只要数据源发生变化,其会立即重新渲染视图模板,ng-repeat经过了高度的优化,以便于对DOM书的影响最小化。

:ng-switch on 结合ng-switch-when使用,还有ng-switch-default,其用法与java重点switch用法差不多,on用于制定参数值,ng-switch-when类似于case 。

你可能感兴趣的:(switch)