zoukankan      html  css  js  c++  java
  • AngularJS快速入门

    记得第一次听说AngularJS这项很赞的Web的前端技术,那时还是2014年,年中时我们我的一个大牛兄弟当时去面试时,被问到了是否熟悉该技术,当时他了解和使用的技术比较多。我们询问他面试情况时,他给俺这个菜菜科普了该技术,印象比较深的是该技术支持前端MVC架构,可以完成大部分原有的后台工作,当时就觉得很神奇,但由于自身技术基础比较薄弱,没有太多时间和积累去学习新的技术,因而搁置了。在2016新年初始,正好有一些富余时间,正好学习下这个被称为就是“”两个大括号“”的前端框架(当前已经非常成熟,国内大部分公司的部分项目均已使用),补补我薄弱无比的前端技术,当目前为止,写JS代码仍然是非常的抓瞎。

     

    AngularJS诞生于2009,被用在很多我们熟知的Google应用,例如Gmail、Maps,它主要致力于快捷的构建AJAX应用,在示例库在Github的地址为:https://github.com/shyamseshadri/angularjs-book

    其最基本的几个概念如下所示:

    1. 客户端模板:在我们过去使用的多页应用程序中,我们将html和数据装配混合起来生成页面后发送到浏览器,而单页面的AJAX应用则是将html模板和数据都直接发送给浏览器,由客户端装配。
    2. MVC,概念在所有的Web应用中基本上都使用到。
    3. 数据绑定,支持双向绑定,其实也就是观察者模式的实现,非常的方便。
    4. 依赖注入,通过$scope, $location等内置对象,使得我们只需关心实际需求,而不关心其依赖,遵循了迪米特法则(最少知识原则,Law_of_Demeter)。
    5. 指令,框架提供了很多指令,对html和Dom进行扩展,例如ng-controller指定控制器视图的某一部分,ng-model用于将输入数据绑定到模型属性。

    一个简单例子如下,主要注意的是,很多地方的入门demo会省略ng-app后面的参数,Angular的Controller形式,以及相关模块的绑定等,浏览器肯能会报错,初学需要小心。此外,VS关于AngularJS的智能感知插件的下载和使用也是一个常见问题。

     1 <!DOCTYPE html>
     2 <html ng-app="myApp" xmlns="http://www.w3.org/1999/xhtml">
     3 <head>
     4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     5 <title>Shopping Cart</title>
     6 </head>
     7 <body ng-controller="CartController">
     8 <h1>Your Order</h1>
     9 <div ng-repeat="item in items">
    10 <span>{{$index + 1}}</span>
    11 <span>{{item.title}}</span>
    12 <input ng-model="item.quantity" />
    13 <span ng-bind=" item.price | currency"></span>
    14 <span>{{item.price * item.quantity | currency}}</span>
    15 <button ng-click="remove($index)">Remove</button>
    16 </div>
    17 <script src="../Scripts/angular.js"></script>
    18 <script>
    19 var app = angular.module('myApp', []);
    20 app.controller('CartController', function($scope) {
    21 $scope.items = [
    22 { title: 'Paint pots', quantity: 8, price: 3.95 },
    23 { title: 'Polka dots', quantity: 17, price: 12.95 },
    24 { title: 'Pebbles', quantity: 5, price: 6.95 }
    25 ];
    26  
    27 $scope.remove = function (index) {
    28 $scope.items.splice(index, 1);
    29 }
    30 });
    31 </script>
    32 </body>
    33 </html>
    View Code

    在上例中,我们可以看到通过ng-app声明边界,即告诉框架哪一部分受其管理,以上为div元素;{{greeting.text}}的双括号插值语法,以及相同功能的ng-bind,推荐后者;ng-app命名空间的使用,控制angular框架的有效范围,这样可以很好的与遗留程序兼容;ng-repeat迭代数据;ng-model绑定数据,这是个双向绑定,View中的修改会影响到model,之后会有表单输入的例子再次强化这个概念;ng-click绑定单击事件处理函数。

    大体来说,Angular程序一次请求的流程:用户请求应用起始页;浏览器向服务器发起http连接,加载index.html模板页面;Angular被加载到页面中,等待页面加载完成,然后查找ng-app指令,用于定义模板边界;之后Augular遍历模板,查找指令和绑定关系,触发注册监听器、执行DOM操作、获取服务器初始化数据;最后连接服务器请求其他数据(Ajax)。这种模板和数据完全分离的方式,非常适合浏览器缓存数据,提升应用性能。

    • 表单输入

    在框架中使用表单元素非常简单,可以通过ng-model将表单元素绑定到模型属性上,达到双向绑定的目的,这部分和.NET中的数据绑定效果一致;在表单提交时,ng-submit会自动阻止浏览器默认的POST操作;$watch可以监视Model中具体的属性和字段,而ng-change主要用来检视表单元素;ng-show和ng-hide用于显隐元素,在菜单场景下应用广泛

     1 <body ng-app="myApp">
     2 <form ng-controller="SomeController" ng-submit="requestFunding()">
     3 <input type="checkbox" ng-model="youCheckIt" />
     4 <br />
     5 <input ng-change="computeNeeded()" ng-model="funding.startEstimate" />
     6 Recommendation:{{funding.needed}}
     7 <br />
     8 <button>Fund my startup</button>
     9 <br />
    10 <button ng-click="reset()">Reset</button>
    11 </form>
    12 <script>
    13 var app = angular.module('myApp', []);
    14 app.controller('SomeController', function ($scope) {
    15 var funding = {};
    16 funding.startEstimate = 0;
    17 funding.needed = 0;
    18 $scope.funding = funding;
    19 
    20 var computeNeeded = function () {
    21 $scope.funding.needed = $scope.funding.startEstimate * 10;
    22 };
    23 $scope.$watch('funding.startEstimate', computeNeeded);
    24 $scope.requestFunding = function () { window.alert("Sorry, please get more customer first."); };
    25 $scope.reset = function () { $scope.funding.startEstimate = 0; };
    26 });
    27 </script>
    28 </body>
    View Code

    Tip:

    相信大家接触非侵入式javascript概念已经很久了吧,但通过以上例子,我们会发现angularJS的使用并没有这样做,而是将html模板和相关控制代码混写了,这难道是说该框架并不合理。其实不然,之前提取非侵入式的概念也是因为当时前端开发的痛点:不同浏览器对js的支持不同,运行方式也不同;事件处理器都引用全局命名空间的函数,在集成时存在命名冲突;事件监听器绑定数据结构和行为,难以维护。但对于JS来说,它通过框架自身解决兼容性问题,通过命名空间解决集成的问题,最后一点也是最重要的一点,所有的事件处理函数并不引用任何的DOM元素和事件。

    模块、控制器和数据绑定:无依赖模块angular.module('firstModule', [])

    Scope和Event:scope是内置对象,主要用于处理数据模型,作用范围和页面声明的范围一致$scope.greeting='Hello', {{greeting}},当使用范围不同时,需要通信,就需要借助Event,示例代码如下所示。

    $.scope.$emit('event_emit', 'message');//子scope发送
    $.scope.$on('event_emit', function(event, data){});//父scope接受
    
    $.scope.$broadcast('event_broad', 'message');//父scope发送
    $.scope.$on('event_broad', function(event, data){});//子scope接受

    多视图和路由:需要引入angular-route.js

     1         angular.module('firstModule').config(function($routeProvider) {
     2             $routeProvider.when('/view1', {
     3                 controller : 'Controller1',
     4                 templateUrl : 'view1.html'
     5             }).when('/view2', {
     6                 controller : 'Controller2',
     7                 templateUrl : 'view2.html'
     8             });
     9         });
    10 
    11     <ul>
    12         <li>
    13             <a href='#/view1'>view1</a>
    14         </li>
    15         <li>
    16             <a href='#/view2'>view2</a>
    17         </li>
    18     </ul>
    19 <ng-view></ng-view>
    View Code

    依赖注入: angular.module('firstModule').controller('diController', ['$scope',function($scope){}]);

    Service和Factory:Angular内置类$location, $timeout, $rootScope等服务,同时可以自己提供额外的服务,方式有两种,Service使用时需要new,而Factory不需要。

     1         angular.module('firstModule').service('helloService', function() {
     2             this.sayHello = function(name) {
     3                 alert('Hello ' + name);
     4             }
     5         });
     6         angular.module('firstModule').controller('diController', ['$scope', 'helloService', function($scope, helloService){helloService.sayHello('wlw');}]);
     7         
     8         angular.module('firstModule').service('helloFactory', function() {
     9             return{
    10                 sayHello = function(name) {
    11                     alert('Hello ' + name);
    12                 }
    13             }
    14         });
    15         angular.module('firstModule').controller('diController', ['$scope', 'helloFactory', function($scope, helloFactory){helloFactory.sayHello('wlw');}]);
    View Code

    http操作:支持ajax操作,包括$http.get(url), $http.post(url, data), $http.put(url, data), $http.delete(url), $http.head(url)。

    自定义指令:内置了很多指令,如ng-repeat, ng-show, ng-model等,可以使用一个简短的指令实现一个前端组件,如<date-picker></date-picker>,<input type="text" class="date-picker" />。

            angular.module('myApp', []).directive('helloWorld', function() {
                return {
                    restrict : 'AE',
                    replace : true,
                    template : '<h3>Hello, World!</h3>'
                };
            });

    Demo: https://github.com/wanliwang/cayman/tree/master/cm-angularweb 

    参考资料:

    1. 布拉德, 格林. AngularJS开发下一代Web应用[M]. 北京:电子工业出版社, 2013.
    2. 汪云飞. Spring Boot实战[M]. 北京:电子工业出版社, 2016.
  • 相关阅读:
    Codeforces Bubble Cup 8
    Codeforces Bubble Cup 8
    BZOJ 2588: Spoj 10628. Count on a tree 树上跑主席树
    hdu 5279 Reflect phi 欧拉函数
    hdu 5278 Geometric Progression 高精度
    hdu 5428 The Factor 分解质因数
    hdu 5427 A problem of sorting 水题
    Codeforces Gym 100610 Problem A. Alien Communication Masterclass 构造
    Codeforces Gym 100610 Problem K. Kitchen Robot 状压DP
    Codeforces Gym 100610 Problem H. Horrible Truth 瞎搞
  • 原文地址:https://www.cnblogs.com/xiong2ge/p/angularjs_base01.html
Copyright © 2011-2022 走看看