暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

AngularJS入门 & 分页 & CRUD示例

顶哥说 2019-06-01
286

一.AngularJS 简介

AngularJS  诞生于2009年,由Misko Hevery 等人创建,后为Google所收购。是一款优秀的前端JS框架,已经被用于Google的多款产品当中。AngularJS有着诸多特性,最为核心的是:MVC、模块化、自动化双向数据绑定、依赖注入等等。

其中MVC理解如下:

Model : 数据,其实就是 angular变量($scope.xx)

View : 数据的呈现

Controller : 操作数据,就是function,数据的crud

二.AngularJS 用法简介

1.引入文件

    <script type="text/javascript" src="angular.min.js"></script>

    2.使用标签

    2.1 ng-app:  (定义AngularJS根元素)

    body标签中的 ng-app 表示从此到body 结束范围已经被 angularJS接管, 在此区域可使用 angularJS 表达式及指令。

    {{ }}:双括号,是 angularJS 插值表达式,利用括号获取值,同时也可以在花括号中编写表达式。

      <body ng-app>
      {{100+100}}
      </body>

      2.2 ng-model:  (双向绑定)

      ng-model 指令用于绑定变量/表单元素,这样用户在文本框输入的内容会绑定到变量上,而表达式可以实时的输出变量。

        <body ng-app>
        请输入姓名:<input ng-model="name" type="" name="">
        {{name}}
        </body>

        2.3 ng-init: (初始化)

        ng-init 指令可以对变量初始化,还可以进行方法初始化调用(ng-init="findAll()",页面刷新findAll方法会自动被调用)。

          <body ng-app ng-init="name='song'">
          {{name}}
          </body>

          2.4 模块化设计

          使用模块化的开发方式管理js:      var  app = angular.module("dintalk", [])

          2.5 ng-controller: (指定控制器)

          $scope 的贯穿整个AngularJS App应用,所有变量,函数,对象全都绑定在$scope对象中,它在视图和控制器间建立一个通道,基于作用域视图在修改数据时会立刻更新 $scope,同样的$scope 发生改变时也会立刻重新渲染视图 。

            ...
            <script type="text/javascript">
            var app = angular.module("dintalk",[]);
            //$scope 是控制层和视图层交换数据的桥梁
            app.controller('myController', function($scope){
            $scope.add=function(){ // 调用方法时注意加括号: add()
            return $scope.x+$scope.y;
            }
            })
            </script>
            </head>
            <body ng-app="dintalk" ng-controller="myController" >
            第一个数:<input ng-model="x" >
            第二个数:<input ng-model="y" >
            {{add()}}
            </body>

            2.5 ng-click: (常用的单击事件)

              ...
              var app = angular.module("dintalk",[]);
              //$scope 是控制层和视图层交换数据的桥梁
              app.controller('myController', function($scope){
              $scope.add=function(){
              $scope.z = Number($scope.x) + Number($scope.y);
              }
              })
              </script>
              </head>
              <body ng-app="dintalk" ng-controller="myController" >
              第一个数:<input ng-model="x" >
              第二个数:<input ng-model="y" >
              <button ng-click="add()">运算</button>
              结果:{{z}}
              </body>

              2.6 ng-repeat: (循环数组)

                //定义一个模块
                var app = angular.module("dintalk", []);
                //定义模块函数
                app.controller("myController", function ($scope) {
                //定义数组
                $scope.list = [99,100,1000,10000];
                })
                </script>
                </head>
                <body ng-app="dintalk" ng-controller="myController">
                <ul>
                <li ng-repeat="arr in list">
                {{arr}}
                </li>
                </ul>

                2.7 ng-repeat: (循环对象数组)

                  var app = angular.module("dintalk",[]); 
                  //$scope 是控制层和视图层交换数据的桥梁
                  app.controller('myController', function($scope){
                  $scope.list = [{"name":"cgx","age":"18"},{"name":"aj","age":"19"},{"name":"zbz","age":"20"}];
                  })
                  </script>
                  </head>
                  <body ng-app="dintalk" ng-controller="myController" >
                  <table>
                  <tr>
                  <td>姓名</td>
                  <td>年龄</td>
                  </tr>
                  <tr ng-repeat="x in list">
                  <td>{{x.name}}</td>
                  <td>{{x.age}}</td>
                  </tr>
                  </table>
                  </body>

                  2.8 $http : (发送ajax请求)

                  $http.get(url).success(function(data){})

                  $http.post(url,params).success(function(data){})

                  三.AngularJS 的分页

                  第一步:引入分页插件

                    <!-- 引入AngularJS及其分页插件和分页样式 -->
                    <script src="../plugins/angularjs/angular.min.js"></script>
                    <script type="text/javascript" src="../plugins/angularjs/pagination.js"></script>
                    <link rel="stylesheet" href="../plugins/angularjs/pagination.css">


                    <script type="text/javascript">
                    //1.定义模块,中括号内引入分页插件
                    var app = angular.module('pinyougou', ['pagination']);
                    //2.创建控制器 Controller
                    app.controller('brandController', function ($scope, $http) {
                    ...

                    第二步:页面中定义分页栏显示区域

                      <!--数据列表-->
                      ...
                      <!--数据列表-->
                      <!--分页插件-->
                      <tm-pagination conf="paginationConf"/>

                      第三步:控制器Controller中设置分页参数,并定义分页查询方法

                        app.controller('brandController', function ($scope, $http) {
                        // 1.定义分页查询的方法
                        $scope.findPage = function () {
                        // 使用ajax异步请求的方式
                        $http.get('../brand/findPage.do?pageNum=' + $scope.paginationConf.currentPage +
                        "&pageSize=" + $scope.paginationConf.itemsPerPage).success(
                        function (response) {
                        $scope.list = response.rows; //显示的list内容
                        //将总记录数设置到分页插件参数上
                        $scope.paginationConf.totalItems = response.total;
                        }
                        )
                        }


                        //2.设置分页的参数配置
                        $scope.paginationConf = {
                        currentPage: 1, //当前页
                        totalItems: 10, //总记录数
                        itemsPerPage: 10, //每页记录数
                        //分页选项,下拉选择一页多少条记录
                        perPageOptions: [10, 20, 30, 40, 50, 60],
                        onChange: function () { //页面变更后触发的方法
                        $scope.findPage(); //启动就会调用分页组件
                        }
                        };
                        ...

                        四.AngularJS 的CRUD

                        1.分页查询后台返回结果的封装实体

                          /**
                          * 分页查询的响应结果,内含总记录数和当前页的数据列表
                          * @author Mr.song
                          * @date 2019/06/01 15:49
                          */
                          public class PageResult implements Serializable {


                          private Long total; // 总记录数
                          private List rows; //数据记录列表


                          public PageResult(Long total, List rows) {
                          this.total = total;
                          this.rows = rows;
                          }
                          //setter&getter
                          ...
                          }

                          2.增删改后台返回的结果封装

                            /**
                            * 增删改操作的结果实体,封装结果和响应消息
                            * @author Mr.song
                            * @date 2019/06/01 15:47
                            */
                            public class Result implements Serializable {


                            private Boolean success; //操作是否成功
                            private String Message; //响应消息


                            public Result(Boolean success, String message) {
                            this.success = success;
                            Message = message;
                            }
                            //setter&getter
                            ...
                            }

                            3.crud 的页面链接

                              <!-- 1. 新建时清空实体数据(双向绑定的数据):ng-click="entity={}" -->
                              <button ng-click="entity={}" type="button" class="btn btn-default" title="新建" data-toggle
                              ="modal" data-target="#editModal"><i class="fa fa-file-o"></i> 新建
                              </button>
                              <!-- 2. 删除 -->
                              <button ng-click="del()" type="button" class="btn btn-default" title="删除"><i
                              class="fa fa-trash-o"></i> 删除
                              </button>
                              <!-- 3. 更新 (遍历展示数据) -->
                              <tr ng-repeat="item in list">
                              <td><input ng-click="updateSelection(item.id,$event)" type="checkbox"></td>
                              <td>{{item.id}}</td>
                              <td>{{item.name}}</td>
                              <td>{{item.firstChar}}</td>
                              <td class="text-center">
                              <button ng-click="findOne(item.id)" type="button" class="btn bg-olive btn-xs"
                              data-toggle="modal" data-target="#editModal">修改
                              </button>
                              </td>
                              </tr>
                              <!-- 4.新建或更新时的保存 -->
                              <button ng-click="save()" class="btn btn-success" data-dismiss="modal" aria-hidden="true">
                              保存
                              </button>

                              4.crud的控制器Controller方法

                                <script type="text/javascript">
                                //1.定义模块,中括号内引入分页插件
                                var app = angular.module('dintalk', ['pagination']);
                                //2.创建控制器 Controller
                                app.controller('brandController', function ($scope, $http) {
                                //========================= 查询 =============================
                                // 1.定义分页查询的方法
                                $scope.findPage = function () {
                                // 使用ajax异步请求的方式
                                $http.get('../brand/findPage.do?pageNum=' + $scope.paginationConf.currentPage +
                                "&pageSize=" + $scope.paginationConf.itemsPerPage).success(
                                function (response) {
                                $scope.list = response.rows; //显示的list内容
                                //将总记录数设置到分页插件参数上
                                $scope.paginationConf.totalItems = response.total;
                                }
                                )
                                }


                                //2.设置分页的参数配置
                                $scope.paginationConf = {
                                currentPage: 1, //当前页
                                totalItems: 10, //总记录数
                                itemsPerPage: 10, //每页记录数
                                perPageOptions: [10, 20, 30, 40, 50, 60], //分页选项,下拉选择一页多少条记录
                                onChange: function () {//页面变更后触发的方法
                                $scope.findPage(); //启动就会调用分页组件
                                }
                                };
                                //========================= 查询 =============================
                                //========================= 新增和更新 ========================
                                //1.定义新增和更新时保存表单数据的变量
                                $scope.entity = {};


                                //2.新增/更新的保存方法 : 根据是否有id,判断是新增还是更新
                                $scope.save = function () {
                                if ($scope.entity.id == null) { //新增
                                $http.post('../brand/insert.do', $scope.entity).success(
                                function (response) {
                                //新增成功刷新页面
                                if (response.success) { //Result success,message
                                $scope.findPage(); //刷新(调用查询方法)
                                } else {
                                alert(response.message);
                                }
                                }
                                )
                                } else { //修改
                                $http.post('../brand/update.do', $scope.entity).success(
                                function (response) {
                                //新增成功刷新页面
                                if (response.success) { //Result success,message
                                $scope.findPage(); //刷新(调用查询方法)
                                } else {
                                alert(response.message);
                                }
                                }
                                )
                                }
                                }


                                //3.更新时的数据回显
                                $scope.findOne = function (id) {
                                $http.get('../brand/findOne.do?id=' + id).success(
                                function (response) {
                                //因为是双向绑定,因此给entity赋值即可
                                $scope.entity = response;//{id:xxx,name:'xxx',firstChar:'xxxx'}
                                }
                                )
                                }
                                //========================= 新增和更新 ========================
                                //========================= 删除 ==============================
                                //1.品牌删除方法
                                $scope.del = function () {
                                $http.get('../brand/delete.do?ids=' + $scope.selectIds).success(
                                function (response) {
                                //删除成功刷新页面
                                if (response.success) { //Result success,message
                                $scope.findPage(); //刷新
                                //删除成功,情况id数组
                                $scope.selectIds = [];
                                } else {
                                alert(response.message);
                                }
                                }
                                )
                                }


                                //2.定义数组保存用户勾选的ids
                                $scope.selectIds = [];
                                //3.页面数据的复选框点击事件调用该方法
                                $scope.updateSelection = function (id, $event) {
                                if ($event.target.checked) { //check是勾选状态
                                $scope.selectIds.push(id); //$scope.selectIds压入对象(存入id)
                                } else {
                                //$scope.selectIds.indexOf(id)获取当前id所在位置,splice是前端数组移除(需要两个参数)
                                //参数一:id在数组的位置,参数二:删除个数
                                $scope.selectIds.splice($scope.selectIds.indexOf(id), 1);
                                }
                                }
                                //========================= 删除 ==============================
                                })
                                </script>


                                文章转载自顶哥说,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

                                评论