走进AngularJS

   前  言 

AngularJS 通过新的属性和表达式扩展了 HTML。

使用起来非常方便。

1. AngularJS的指令与表达式
AngularJS 通过 指令 扩展了 HTML,且通过 表达式 绑定数据到 HTML。

1.1AngularJS表达式

     AngularJS使用 {{}} 绑定表达式。用于将表达式的内容输出到页面中
     表达式中可以是文字、运算符、变量等,也可以在表达式中进行运算输出结果。
      eg: <p>{{5+5+"Angular"}}</p>
 
     如果Angular.js文件放在页面下方,在页面刷新的瞬间会看到{{}}表达式的原样,
     所以可以使用ng-bind指令替代表达式。
      eg:上式可改写为:<p ng-bind="5+5+'Angular'"></p>
 

1.2AngularJS的常用指令

AngularJS 指令是扩展的 HTML 属性,带有前缀 ng-。
1.2.1 ng-app:声明AngularJS所管辖的区域。一般写在body或者html标签上,原则上一个页面只能有一个。
      eg:<body ng-app=""></body>
   
1.2.2 ng-model: 指令把元素值(比如输入域的值)绑定到应用程序的变量中。
       eg:<input type="text" ng-model="name"/>
 
1.2.3 ng-bind:把应用程序变量中的值,输出到页面HTML视图中。可以与表达式{{}}互相替换
      eg:<div ng-bind="name"></div>
   
1.2.4 ng-init:初始化AngularJS应用程序中的变量值。
      eg:<body ng-app="" ng-init="name='jredu'">
      应用程序初始化时,name变量就赋有初值。
 
2. AngularJS中的MVC与作用域

2.1MVC三层架构

  Model(模型层):应用程序中用于处理数据的部分。(包括将数据保存或修改到数据库、变量、文件中)

                             在AngularJS中,Model特指的是:应用程序中的各种数据。
      
View(视图层):用户可以看到的用户显示数据的页面。
  
Controller(控制器):控制器是链接View与Model的桥梁。负责从View读取数据,接收用户操作输入,并将数据发送给Model层。Model层
                                  将数据处理完毕后,将结果返给Controller,Controller再将结果返回给View层显示。
          View →(数据) → Controller → (数据)
            ↗                                                          ↘
       用户                                                 Model(处理数据)
            ↖                                                          ↙
            View ←(结果) ← Controller ← (结果)
 

2.2创建模块

2.2.1 创建一个Angular的模块。即ng-app=" "所需要绑定的部分。
         需要接收两个参数:
        ① 模块名称,即ng-app双引号中需要绑定的名字。<body ng-app="myApp">
        ② 数组:表示需要注入的模块名称,不需要注入其他模块可用空数组代替。
 
       >>> Angular将常用的功能封装到angular.js,创建主模块时直接可以使用,无需注入。
       >>> 而一些应用较少的功能,需要导入对应的JS文件,并且在[]中注入进这个模块,才能够使用。
       这就是AngularJS中的【模块化开发】与【依赖注入】!
      var app=angular.module("myApp",[]);
 
2.2.2 在AngularJS的模块上,创建一个控制器,需要传入两个参数:
     ① 控制器名称,即ng-controller需要绑定的名称。
           <div ng-controller="myCtrl">
     ② 控制器的构造函数,构造函数可以传入多个参数。
     >>> 如果要在函数中使用系统的内置对象,则必须通过函数的参数传入,否则不能使用
     >>> AngularJS中的内置对象,都用$开头,例如$scope,$rootScope

2.3AngularJS中的作用域

2.3.1 $scope局部作用域,声明在$scope上的属性和方法,只能在当前Controller使用
2.3.2 $rootScope根作用域。声明在$rootScope上的属性和方法,可以在整个ng-app所包含的范围使用。
 
>>>  如果没有使用$scope声明变量,而是直接使用ng-model在HTML标签中绑定的数据的作用域为:
      1、如果ng-model写在某个Controller中,则这个变量会默认绑定到当前Controller的$scope上;
      2、如果ng-model没有写在任何一个Controller中,则这个变量会默认绑定到$rootScope
    
>>>  AngularJS中的父子作用域!
     1、AngularJS中,子作用域只能访问父作用域中的变量,而不能修改父作用域中的变量
     2、为了解决上述问题,可以将父作用域中的变量声明为引用数据类型,例如对象等。这样可以在子作用域中,直接修改对象的属性,
          而不需要修改对象本身保存的地址。
 
3. AngularJS中的过滤器
过滤器可以使用一个管道字符(|)添加到表达式和指令中。
>>> 系统内置的过滤器
      currency      将数字格式化为货币格式
      filter              从数组项中选择一个子集
      lowercase    格式化字符串为小写
      orderBy        根据某个表达式排列数组
      uppercase    格式化字符串为大写
        angular.module("app",[])
        .controller("ctrl",function($scope){
            $scope.classes=[
                {name:"张三",age:12,score:78},
                {name:"李四",age:12,score:66},
                {name:"二麻子",age:12,score:98},
                {name:"小刘",age:12,score:54},
                {name:"八万",age:12,score:75},
            ]
        })
        /*
         * 自定义过滤器
         */
        .filter("showHello",function(){
            return function(text){
                return "Hello AngularJS";
            }
        })
        .filter("reverse",function(){
            return function(text){
                return text.split("").reverse().join("");
            }
        })
        /*
         * 自定义过滤器,同时需要传递过滤参数
         * 调用过滤器示例:<p>{{12345678901| hideTel:4}}</p>
         * 传入的参数4,将被过滤函数的num形参所接受
         */
        .filter("hideTel",function(){
            return function(text,num){
                num=num>0&&num<11?num:3;
                text=text+"";
                var newText=text.substring(0,11-num)
                          +text.substring(11-num,11).replace(/d/g,"*");
                return newText;
            }
        })
        /*
         * 自定义过滤器,实现根据姓名筛选数据的功能。
         * >>> 调用示例:
         *             请输入姓名:<input type="text" ng-model="name"/>
         *        <tr ng-repeat="item in classes | filterByName:name">
         */
        .filter("filterByName",function(){
            return function(items,search){
                if(!search) return items;
                var arr=[];
                for (var i=0;i<items.length;i++) {
                    var index=items[i].name.indexOf(search);
                    if (index>-1) {
                        arr.push(items[i]);
                    }
                }
                return arr;
            }
        })
4. AngularJS中的service & factory & provider

4.1service

4.1.1 内置服务

       >>> 要使用服务必须要把服务名通过controller的构造函数的参数注入进来!!!
       >>> 系统内置的服务,同意使用$开头,服务中的属性和方法统一使用$$开头!!
              自定义服务时,需要注意与系统服务的写法区分开
              $location:返回当前页面的URL地址信息,是一个对象;
              $http:向服务器发送请求,类似于JQuery中的Ajax;
              $timeout:相当于 setTimeout();
              $interval: 相当于setInterval();
        angular.module("app",[])
        .controller("ctrl",function($scope,$location,$timeout,$interval,hexafy){
            $scope.local = $location.$$host;
            $timeout(function(){
                $scope.time="我是两秒钟之后出现!";
            },2000);
            $scope.num=0;
            $interval(function(){
                $scope.num++;
            },1000);
            $scope.gongneng=hexafy.gongneng;
            $scope.num1=hexafy.func(10);
        })
4.1.2  自定义服务
          第一个参数是服务名;
          第二个参数是自定义服务的构造函数。我们自定义的服务,本质是一个对象。
         对象的属性,可以在构造函数中,使用this.属性 表示;
         对象的方法,可以在构造函数中,使用this.方法 表示;
        .service("hexafy",function(){
            this.gongneng="将十进制数转化为16进制";
            this.func=function(num){
                return num.toString(16);
            }
        })
        /*使用过滤器实现同样功能*/
        .filter("filter1",function(){
            return function(num){
                return num.toString(16);
            }
        })
        /* 在过滤器中调用服务!!
         * 也必须在声明过滤器的外层构造函数中,注入服务名称!!
         */
        .filter("filter2",function(hexafy,$location){
            return function(num){
                return hexafy.func(num);
            }
        })

4.2factory

factory服务在使用上与service服务没有太大差距。
唯一的不同点,是声明服务时,factory服务是在函数中先声明好一个对象,然后使用return将对象返回。
而service服务,则是直接在函数中使用this将属性和方法添加到对象上面。
        angular.module("app",[])
        .controller("ctrl",function($scope,hexafy){
            $scope.gongneng=hexafy.gongneng;
            $scope.num1=hexafy.func(11);
        })
        .factory("hexafy",function(){
            var obj={
                gongneng:"将十进制数转化为16进制",
                func:function(num){
                    return num.toString(16);
                }
            }
            return obj;
        })

4.3provider

4.3.1 在AngularJS中,service服务、factory服务都是基于provider服务实现的;
4.3.2 在定义provider时,可以使用this.$get 方法,接收一个函数,函数里面采用与factory完全相同的写法!!!
        .provider("hexafy",function(){
            this.$get=function(){
                var obj={
                    gongneng:"333"
                }
                return obj;
            }
        })
4.3.3 在三种服务中,provider服务是唯一一个可以写进config配置阶段的服务。
         所以说,如果服务需要在配置阶段,也就是在声明controller之前执行的话,则可以使用provider;否则一般使用service或factory
        angular.module("app",[])
        /*.config()表示配置阶段,在声明controller之前执行。可以用于声明一些在controller中
         * 需要使用的全局变量、方法、服务等
         */
        .config(function($provide){
            // 在配置阶段声明provider服务,需要在config中注入系统对象$provide
            $provide.provider("hexafy",function(){
                this.$get=function(){
                    var obj={
                        gongneng:"444"
                    }
                    return obj;
                }
            });
        })
        .controller("ctrl",function($scope,hexafy){
            $scope.gongneng=hexafy.gongneng;
        })
5. AngularJS中的select和表格

5.1使用数组作为数据源

5.1.1 item表示数组中的每一项;
5.1.2 循环出的option中,value的值,默认为item;
5.1.3 option显示出的内容(<option></option>标签中的文字)是由item.site for 决定的;
        <select ng-model="site2" ng-options="item.site for item in sites"></select>
        <!--
            这种写法,默认生成的option效果如下:
            <option value="http://www.google.com">Google</option>
        -->

5.2以对象作为数据源

5.2.1 (key,value) 第一项表示对象的键,第二组表示对象的值;
5.2.2 option的value,永远都是对象的值!
5.2.3 option显示出的内容(<option></option>标签中的文字)是由... for 决定的!也就是说for前面是什么,option标签中就是什么。
        <select ng-model="site3" ng-options="key for (key,value) in sitess">
            <!--
                <option value="value">key/value(取决for前面的内容)</option>
            -->
        </select>
            <tr ng-repeat="item in options">
                <!--
                    ng-repeat遍历是,$index 表示当前的行索引!
                -->
                <td>{{$index + 1}}</td>
                <td>{{item}}</td>
            </tr>
ng-options 和 ng-repeat
1、 ng-options使用时,是将指令添加在select上;
      ng-repeat使用时,是将指令添加在option上;
2、 ng-options使用时,必须同步给select标签绑定ng-model;
       ng-repeat使用时,不一定绑定ng-model;
3、ng-options使用时,只需要关心for前面的部分,即option标签中显示的文字,而option的value会自动分配,不由我们决定
      (使用数组作为数据源时,value就是数组的每一项;使用对象作为数据源时,value永远都是对象的值)
      ng-repeat使用时,除了要制定option标签中要显示的文字,还需要手动指定value中的内容,如果没有指定则默认没有value
 
6. AngularJS中的表单和输入验证

6.1表单中,常用的验证操作

$dirty       表单有填写记录
$valid      字段内容合法的
$invalid   字段内容是非法的
$pristine  表单没有填写记录
$error      表单验证不通过的错误信息
 

6.2验证

6.2.1 验证时,必须给form和input,设置name属性。
        给form和input设置name后,会自动将表单信息绑定到$scope作用域中。所以,可以直接使用formName.inputName.$验证操作,
        得到验证结果。
        例如:
              formName.inputName.$dirty="true";表示表单被填写过;
              formName.inputName.$invalid="true";表示表单输入内容不合法;
              formName.inputName.$error.required="true";表示设置了必填但是没有输入;
     注意:
            $error支持的验证:required/minlength/maxlength/patten/email/number/date/url等
  
6.2.2  为了避免AngularJS的验证与HTML5的表单验证冲突!!比如说typr="email" required等,H5也会进行验证,那么可以给form添加
         "novalidate"属性,禁用HTML5的验证内容
eg:
    <div class="container" style=" 500px;margin: 50px auto;padding: 0px;">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <div class="panel-title text-center">
                    用户注册
                </div>
            </div>
            <div class="panel-body">
                <form class="form-horizontal" name="form" novalidate>
                    <div class="row">
                        <div class="col-xs-3">用户名</div>
                        <div class="col-xs-9">
                            <input type="text"class="form-control"name="name"  ng-model="user.name" 
                            ng-minlength="6" ng-maxlength="12"/>
                            <p style="margin: 0px; color: red;" ng-show="form.name.$invalid && form.name.$dirty">
                                <span ng-show="form.name.$error.required">用户名必须填写</span>
                                <span ng-show="form.name.$error.minlength">用户名长度最小为6位</span>
                                <span ng-show="form.name.$error.maxlength">用户名长度最大为16位</span>
                            </p>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-3">邮箱:</div>
                        <div class="col-xs-9">
                            <input type="email" class="form-control" name="email" ng-model="user.email" required/>
                            <p style="margin: 0px;color: red;" ng-show="form.email.$invalid && form.email.$dirty">
                                <span ng-show="form.email.$error.required">邮箱必须填写</span>
                                <span ng-show="form.email.$error.email">邮箱不合法</span>
                            </p>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-3" >密码:</div>
                        <div class="col-xs-9">
                            <input type="password"class="form-control"name="pwd" ng-model="user.pwd"
                                pattern="^w{6,18}$" required/>
                            <p style="margin: 0px; color: red;" ng-show="form.pwd.$invalid && form.pwd.$dirty">
                                <span ng-show="form.pwd.$error.pattern">密码只能由6-18位的字母、数字、下划线</span>
                            </p>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-3" >确认密码:</div>
                        <div class="col-xs-9">
                            <input type="password"class="form-control" name="repwd" ng-model="user.repwd" required/>
                            <p style="margin: 0px; color: red;" ng-show="user.pwd!=user.repwd && form.repwd.$dirty">
                                两次密码输入不一致
                            </p>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-5">
                            <input type="submit" value="注册" class="btn btn-success" ng-disabled="form.$invalid||user.pwd!=user.repwd"/>
                        </div>
                        <div class="col-xs-5">
                            <input type="reset" value="重置" class="btn btn-warning"/>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
原文地址:https://www.cnblogs.com/sin0/p/7592123.html