• Angular指令


    一、指令

    基础指令

    1、ng-disabled

    使用ng-disabled可以把disabled属性绑定到以下表单输入字段上: <input> ( text、 checkbox、 radio、 number、 url , email 、 submit); <textarea> ; <select> ; <button> 。

    案例1:
    <input type="text" ng-disabled="true" placeholder="TypetoEnable">

    在下面的例子,文本字段会被禁用五秒,直到在$timeout中将isDisabled属性设置为true:

    <textarea ng-disabled="isDisabled">Wait5seconds</textarea>
    angular.module('myApp', [])
    .run(function($rootScope, $timeout) {
     $rootScope.isDisabled = true;
     $timeout(function() {
     $rootScope.isDisabled = false;
     }, 5000);
    });  
    

    2、ng-select

    用来将数据同HTML的<select> 元素进行绑定。这个指令可以和ng-model 以及ng-options指令一同使用,构建精细且表现优良的动态表单。

    3、ng-options

    ng-options的值可以是一个内涵表达式注意上边option位置是怎么写的? 接受一个数组或对象,并对它们进行循环,将内部的内容提供给select标签内部的选项。

    演示代码:

    angular.module('myApp',[])
                .controller('myController',function($scope) {
                    $scope.cities = [
                        {name: 'Seattle'},
                        {name: 'San Francisco'},
                        {name: 'Chicago'},
                        {name: 'New York'},
                        {name: 'Boston'}
                    ];
                });
    
     <select ng-model="city"
                ng-options="city.name for city in cities">
            <option value="">Choose City</option>
        </select>
        Best City: {{ city.name }}  
    

    4、ng-submit

    ng-submit用来将表达式同onsubmit事件进行绑定。这个指令同时会阻止默认行为(发送请 求并重新加载页面), 除非表单不含有action属性。

    演示代码:

    <form ng-submit="submit()"
          ng-controller="FormController">
        Enter text and hit enter:
        <input type="text"
               ng-model="person.name"
               name="person.name" />
        <input type="submit" value="Submit" />
    </form>
    <script type="text/javascript">
        angular.module('myApp',[])
                .controller('FormController',function($scope) {
                    $scope.person = {};
                    $scope.submit = function() {
                      alert($scope.person.name)
                    };
                });
    </script>  
    

    5、ng-app

    任何具有ng-app属性的DOM元素将被标记为$rootScope的起始点。

    演示代码:

    <div ng-app="myApp">
        {{ someProperty }}
        <button ng-click="someAction()">测试</button>
    </div>
    <script type="text/javascript">
        angular.module('myApp', [])
                .run(function($rootScope) {  //注意这里的run方法,我们之前就用过几次,后边会在module加载的时候解释,现在用就可以了
                    $rootScope.someProperty = 'hello world';
                    $rootScope.someAction = function() {
                        $rootScope.someProperty = '你好世界';
                    };
                });
    </script>  
    

    6、ng-controller

    内置指令ng-controller的作用是为嵌套在其中的指令创建一个子作用域,避免将所有操作 和模型都定义在$rootScope上。用这个指令可以在一个DOM元素上放置控制器。

    $scope只是一个JavaScript对象,其中含有从父级$scope中通过原型继承得到的方法和属性,包括应用的$rootScope。

    嵌套在ng-controller中的指令有访问新子$scope的权限,但是要牢记每个指令都应该遵守的和作用域相关的规则。 注意:$scope对象的职责是承载DOM中指令所共享的操作和模型。

    演示代码:

    <div ng-app="myApp">
        <div ng-controller="myController">
        {{ someModel.someProperty }}
        <button ng-click="someAction()">click me</button>
    </div>
    </div>
    <script type="text/javascript">
        angular.module('myApp',[])
                .controller('myController', function($scope) {
                    //创建模型
                    $scope.someModel = {
                        // 添加属性
                        someProperty: 'hello world'
                    }
                    // 设置$scope自身的操作
                    $scope.someAction = function() {
                        $scope.someModel.someProperty =' 你好世界';
                    };
                });
    </script>  
    

    案例2:之前作用域嵌套

    <div ng-app="myApp">
        <div ng-controller="SomeController">
            {{ someBareValue }}
            <button ng-click="someAction()">Communicate to child</button>
            <div ng-controller="ChildController">
                {{ someBareValue }}
                <button ng-click="childAction()">Communicate to parent</button>
            </div>
        </div>
    </div>
    </div>
    <script type="text/javascript">
        angular.module('myApp', [])
                .controller('SomeController', function($scope) {
                    // 反模式,裸值
                    $scope.someBareValue = 'hello computer';
                    // 设置 $scope 本身的操作,这样没问题
                    $scope.someAction = function() {
                        // 在SomeController和ChildController中设置{{ someBareValue }}
                        $scope.someBareValue = 'hello human, from parent';
                    };
                })
                .controller('ChildController', function($scope) {
                    $scope.childAction = function() {
                        // 在ChildController中设置{{ someBareValue }}
                        $scope.someBareValue = 'hello human, from child';
                    };
                });
    </script>  
    

    7、ng-switch

    可以在数据发生变化时渲染不同指令到视图中。

    演示代码:

    <div ng-app>
        <input type="text" ng-model="person.name"/>
        <div ng-switch on="person.name">
            <p ng-switch-default>admin</p>
            <h1 ng-switch-when="zhangsan">{{ person.name }}</h1>
        </div>
    </div>  
    

    8、ng-if

    使用ng-if指令可以完全根据表达式的值在DOM中生成或移除一个元素。如果赋值给ng-if的表达式的值是false,那对应的元素将会从DOM中移除,否则对应元素的一个克隆将被重新插 入DOM中。

    演示代码:

    <div ng-app>
        <div ng-if="2+3===5">
           hello world
        </div>
    </div>
    
    <div ng-app="myApp" ng-controller="myController">
        <div ng-if="test">
            hello world
        </div>
    </div>
    
       angular.module('myApp',[])
                .controller('myController', function($scope) {
                  $scope.test=false;
                });  
    

    重要:

    9、ng-repeat

    ng-repeat用来遍历一个集合或为集合中的每个元素生成一个模板实例。集合中的每个元素都会被赋予自己的模板和作用域。同时每个模板实例的作用域中都会暴露一些特殊的属性。 参数:

    $index:遍历的进度( 0...length-1 )。

    $first:当元素是遍历的第一个时值为true。

    $middle:当元素处于第一个和最后元素之间时值为true。

    $last:当元素是遍历的最后一个时值为true。

    $even:当$index值是偶数时值为true。

    $odd:当$index值是奇数时值为true。

    演示代码:

    <div ng-app="myApp">
        <ul ng-controller="myController" >
            <li ng-repeat="stu in people" ng-class="{even:$even,odd:$odd}" >  //{even:!$even,odd:!$odd}注意
                {{stu.name}} lives in {{stu.city}}
            </li>
        </ul>
    
    </div>
    <script type="text/javascript">
        angular.module('myApp',[])
                .controller('myController',function($scope) {
                    $scope.people = [
                        {name: "Ari", city: "San Francisco"},
                        {name: "Erik", city: "Seattle"},
                        {name: "zhgangsan", city: "chengdu"}
                    ];
                });
    </script>  
    

    10、ng-init

    ng-init指令用来在指令被调用时设置内部作用域的初始状态。 主要用于测试或出示的时候

       <div ng-init="word1='Hello';word2='World'">
            {{word1}} {{word2}}
        </div>  
    

    11、{{ }}

    {{ }} 语法是AngularJS内置的模板语法,它会在内部$scope和视图之间创建绑定。基于这个 绑定,只要$scope发生变化,视图就会随之自动更新。

     <div ng-init="test='HelloWorld'">
                {{test}}
        </div>  
    

    12、bind绑定

    bind绑定——特别说明,之前我们直接绑定的时候{{}}当我们刷新页面或者用户网速比较慢的时候会把{{name}}--这个东西闪烁一下再出来值,bind就是解决方案。

    <div ng-init="test='HelloWorld'">
           <p ng-bind="test"></p>——而且对样式好控制
    </div>  
    

    除使用ng-bind来避免未渲染元素闪烁,还可以在含有{{ }} 的元素上使用ng-cloak指令:

    <body ng-init="greeting='HelloWorld'">
     <p ng-cloak>{{ greeting }}</p>
    </body  
    

    13、ng-cloak

    指令会将内部元素隐藏,直到路由调用对应的页面时才显示出来。——用这种办法同样能去掉闪烁

    <div ng-init="test='HelloWorld'">
               <p ng-cloak>{{test}}</p>
        </div>  
    

    14、ng-bind-template

    同ng-bind指令类似, ng-bind-template用来在视图中绑定多个表达式。

    演示代码:

    <div ng-app="myApp" >
        <div ng-controller="myController">
            <p ng-bind-template="{{name}}{{age  }}"></p>
        </div>
    </div>
    
    </div>
    <script type="text/javascript">
        angular.module('myApp',[])
                .controller('myController',function($scope) {
                    $scope.name ="zhangsan" ;
                    $scope.age=19;
                })
    </script> 
    

    15、ng-show/ng-hide

    ng-show和ng-hide根据所给表达式的值来显示或隐藏HTML元素。当赋值给ng-show指令的 值为false时元素会被隐藏。类似地,当赋值给ng-hide指令的值为true时元素也会被隐藏。

    演示代码:

    <div ng-show="2 + 3 == 5">----和之前的什么优点类似呢?
       hello
    </div>
    
    
     alert($("div").attr("ng-show"))——通过jquery访问一下  
    

    16、ng-click

    ng-click用来指定一个元素被点击时调用的方法或表达式。——之前已经用过

    <body ng-app="myApp" >
    <div ng-controller="myController">
        <button ng-click="count = count + 1"
                ng-init="count=0">
            add
        </button>
        count: {{ count }}
        <button ng-click="subtraction(2)">subtraction</button>
    </div>
    </body>
    
    </div>
    <script type="text/javascript">
        angular.module('myApp',[])
                .controller('myController', function($scope) {
                    $scope.subtraction = function(num) {
                        $scope.count -= num;
                    };
                })
    </script>  
    

    定义指令

    AngularJS应用的模块中有很多方法可以使用,其中directive() 这个方法是用来定义指令的: 用法:

    演示代码:

    angular.module('myApp', [])
    .directive('myDirective', function ($timeout, UserDefinedService) {
     // 指令定义放在这里
    });  
    

    1、directive()

    directive() 方法可以接受两个参数:
    1. name(字符串) 指令的名字,用来在视图中引用特定的指令。 factory_function (函数) 这个函数返回一个对象,其中定义了指令的全部行为。 $compile服务利用这个方法返回的对 象,在DOM调用指令时来构造指令的行为。

    用例:

    <div ng-app="myApp" ng-controller="myController">
            <test></test>
             <span test></span>
           <span class="test"></span>
             <!-- directive:test -->
              <div></div>
    </div>
     var app= angular.module('myApp',[])
             app.directive("test",function(){
                 return{
                     restrict:"AEMC",   ---注意这里的AEMC分别带别什么
                      template:"<span>hello world</span>",
                      replace:true
                 }
             })
    
            template:"<p>hello wolrd <span ng-transclude></span></p>",
                transclude:true  ---注意这是做什么 的
    

    错误示范:

      var app = angular.module('myApp', []);
        app.directive("test",function(){
            return{
              //  scope:{},
                restrict:"AEMC",
                  template:'<div><input type="text" ng-model="name"/>{{name}}</div>',
                  replace:true
        }
        })
      <test></test>
        <test></test>---发生了什么事请?怎么解决  
    

    案例2:在自定义指令中做动作

    <script type="text/javascript">
        var app = angular.module('myApp', []);
        app.controller("myController",["$scope",function($scope){
            $scope.fun=function(){
                alert("hello")
            }
        }])
        app.directive("test",function(){
            return{
                restrict:"AE",
                link:function(scope,element,attr){
                    element.bind("click",function(){
                        scope.$apply("fun()")
                    })
                }
            }
        })
    
    <div ng-app="myApp" ng-controller="myController">
        {{name}}
        <test>点击我啊</test>
    </div>
    

    这里有个关键的字:howToLoad---当页面上的两个地方都要使用同一个link去做一些业务处理的时候。

    演示代码:

    <div ng-controller="myController2">
        <p test howToLoad="fun2()">hello</p>
    </div>
    
    <div ng-controller="myController">
        <p  test howToLoad="fun1()">hello</p>
    </div>
    
    
    
    
    <script type="text/javascript">
        var app = angular.module('myApp', []);
        app.controller("myController",["$scope",function($scope){
            $scope.fun1=function(){
                alert("hello")
            }
        }])
    
        app.controller("myController2",["$scope",function($scope){
            $scope.fun2=function(){
                alert("hello2")
            }
        }])
        app.directive("test",function(){
            return{
                restrict:"AE",
                link:function(scope,element,attr){
                    element.bind("click",function(){
                        scope.$apply(attr.howtoload)
                    })
                }
            }
        })  
    

    angularjs帮我做了一些内置指令之前学过一些,这边它大概帮我们提供了60+种指令 我们现在来看我们最为关心的form指令。

    演示代码:

    <form name="myForm" ng-submit="save()" ng-controller="myController">
            <input type="text" name="userName" ng-model="user.name" required>
            <input type="password" name="pwd" ng-model="user.pwd" required>
            <input type="submit" ng-disabled="myForm.$invalid">
    </form>
    
     var app = angular.module('myApp', []);
       app.controller("myController",["$scope",function($scope){
           $scope.user={}
           $scope.save=function(){
               alert($scope.user.name)
           }
       }])  
    

    模块引入

    在自定义Angular指令时,其中有一个叫做require的字段,这个字段的作用是用于指令之间的相互交流。举个简单的例子,假如我们现在需要编写两 个指令,在linking函数中有很多重合的方法,为了避免重复自己(著名的DRY原则),我们可以将这个重复的方法写在第三个指令的 controller中,然后在另外两个需要的指令中require这个拥有controller字段的指令,最后通过linking函数的第四个参数就可以引用这些重合的方法。

    演示代码:

    var app = angular.modeule('myapp',[]);  
    
    app.directive('parent',function(){  
        return {  
        ...  
        controller: function($scope){  
            this.method1 = function(){  
            };  
            this.method2 = function(){  
            };  
        },  
        ...  
        }  
    });  
    
    app.directive('d1',function(){  
        return {  
        ...  
        require: '^parent',  
        link: function(scope,elem,attrs,parent){  
           parent.method1()
            ..  
            },  
        ...  
        }  
    });    
    

    我们一般引入它:require: 'ngModel',
    我们在require里定义了ngModel 所以这里它是一个NgModelController NgModelController是用来为ng-model提供了一组API。通过他我们可以他来确定ngModel的 值是否是合法的。 我们来做这么一个实验,验证我们的表单中的一些数据是否合法。

    演示代码:

     var app = angular.module('myApp', []);
        app.directive("isUse",function($http){
            return {
                restrict:"A",
                require:"ngModel",
                link:function(scope,element,attr,model){
                    element.bind("blur",function(){
                        scope.$apply(function(){
                            if(scope.username == "abcdefg"){
                                model.isExist = true;
                            }else{
                                model.isExist = false;
                            }
                        });
    
                    });
                }
            };
        });
    <form name="myForm">
        用户名:<input type="text" name="username" ng-model="username" ng-pattern="/^w{6,20}$/" required is-use />
        <span ng-show="myForm.username.$error.required">用户名不能为空</span>
        <span ng-show="myForm.username.$error.pattern">用户名格式不正确</span>
        <span ng-show="myForm.username.isExist">用户名已存在</span>
    </form>  
    

    二、同外界通信: XHR和服务器通信

    $http

    我们可以使用内置的$http服务直接同外部进行通信。 $http服务只是简单的封装了浏览器原生的XMLHttpRequest对象。

    $http服务是只能接受一个参数的函数,这个参数是一个对象,包含了用来生成HTTP请求的配置内容。这个函数返回一个promise对象,具有success和error两个方法。

    演示代码:

    $http({
     method: 'GET',
     url: '/api/users.json'
    }).success(function(data,status,headers,config) {
     // 当相应准备就绪时调用
    }).error(function(data,status,headers,config) {
     // 当响应以错误状态返回时调用
    });  
    

    案例1:

    点击按钮的时候从后台加载数据:

    <body ng-app="myApp">
    <div ng-controller="myController">
    <button ng-click="fun()">click me</button>
    </div>
    <script type="text/javascript">
        angular.module('myApp',[])
                .controller('myController',["$scope","$http",function($scope,$http){
                    $scope.fun=function(){
                        $http({
                            method:'get',
                            url:"data.json"
                        }).success(function(data){
                                    alert(data)
                                })
                    }
                }]);
    </script>  
    

    注意这里http方式完整模式:

    $http({
                method:'POST',
                url:_finalUrl,
                data:_data,
                 headers:{
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }).success(function(data){
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                deferred.reject('Then was an error');
            });
    

    提供的简化方案: 1:post方式提交数据

      angular.module('myApp',[])
                .controller('myController',["$scope","$http",function($scope,$http){
                    $scope.fun=function(){
                   $http.post('data.json').success(function(data){
                       alert(data);
                   })
                }
                }]);
    

    2:get方式

       angular.module('myApp',[])
                .controller('myController',["$scope","$http",function($scope,$http){
                    $scope.fun=function(){
                   $http.get('data.json').success(function(data){
                       alert(data);
                   })
                }
                }]);
  • 相关阅读:
    JVM 关于对象分配在堆、栈、TLAB的理解
    分布式唯一 ID 生成方案有哪些?
    JVM 栈帧之操作数栈与局部变量表 转
    C# TreeHelper帮助类
    Java:Top K问题的解法
    C#单例模式
    C#分组方式比较
    Vue实现登录
    git使用总结
    js实现无色彩球
  • 原文地址:https://www.cnblogs.com/haonantong/p/4662590.html
Copyright © 2020-2023  润新知