1. <!DOCTYPE html>
  2. <html ng-app="myApp">
  3. <head lang="en">
  4. <meta charset="utf-8">
  5. <title>File Upload with AngularJS</title>
  6. <!-- Because we are loading jQuery before AngularJS,
  7. Angular will use the jQuery library instead of
  8. its own jQueryLite implementation -->
  9. <script
  10. src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
  11. </script>
  12. <script
  13. src="http://raw.github.com/blueimp/jQuery-File-Upload/master/js/vendor/
  14. jquery.ui.widget.js">
  15. </script>
  16. <script
  17. src="http://raw.github.com/blueimp/jQuery-File-Upload/master/js/
  18. jquery.iframe-transport.js">
  19. </script>
  20. <script
  21. src="http://raw.github.com/blueimp/jQuery-File-Upload/master/js/
  22. jquery.fileupload.js">
  23. </script>
  24. <script
  25. src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js">
  26. </script>
  27. <script src="app.js"></script>
  28. </head>
  29. <body ng-controller="MainCtrl">
  30. File Upload:
  31. <!-- We will define uploadFinished in MainCtrl and attach
  32. it to the scope, so that it is available here -->
  33. <input id="testUpload"
  34. type="file"
  35. fileupload
  36. name="files[]"
  37. data-url="/server/uploadFile"
  38. multiple
  39. done="uploadFinished(e, data)">
  40. </body>
  41. </html>

到现在为止。我们已经件讲述了AngularJS的绝大部分内容。包括指令,服务,控制器,资源等等。但是我们也知道只看不实践是不行的。有时我们并不关心Angular是怎样工作的。我们只是想知道怎么才能让它工作。

这本本章中。我们会通过给出完整例子,来说明常见问题。

这些例子包括

1、使用jQuery Datepicker

2、Teams List应用:控制器和过滤器的通讯

3、AngularJS中的文件上传

4、私用socket.io

5、使用服务(Servers)

【使用jQuery Datepicker】

源码在github中可见

我们想这样定义我们的datepicker组件

  1. <input datepicker ng-model="currentDate" select="updateMyText(date)"></input>

js这样写

代码很简单。我们来看看特殊的部分。

ng-model

绑定选择事件

调用选择事件

【本例的其他部分】

  1. var app = angular.module('myApp', ['myApp.directives']);
  2. app.controller('MainCtrl', function($scope) {
  3. $scope.myText = 'Not Selected';
  4. $scope.currentDate = '';
  5. $scope.updateMyText = function(date) {
  6. $scope.myText = 'Selected';
  7. };
  8. });

HTML部分

  1. <!DOCTYPE html>
  2. <html ng-app="myApp">
  3. <head lang="en">
  4. <meta charset="utf-8">
  5. <title>AngularJS Datepicker</title>
  6. <script
  7. src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
  8. </script>
  9. <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js">
  10. </script>
  11. <script
  12. src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/
  13. angular.min.js">
  14. </script>
  15. <link rel="stylesheet"
  16. href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
  17. <script src="datepicker.js"></script>
  18. <script src="app.js"></script>
  19. </head>
  20. <body ng-controller="MainCtrl">
  21. <input id="dateField"
  22. datepicker
  23. ng-model="$parent.currentDate"
  24. select="updateMyText(date)">
  25. <br/>
  26. {{myText}} - {{currentDate}}
  27. </body>
  28. </html>

【团队列表APP:过滤器和控制器的通信】

【AngularJS中的文件上传】

另一个常见的用法师上传文件。虽然我们可以通过input type=file来实现,但是。我们现在将要拓展文件上传解决方案。比较好的一个是BlueImp’s File Upload,他使用jQuery和jQueryUI。它的api非常简单

代码如下

  1. angular.module('myApp.directives', [])
  2. .directive('fileupload', function() {
  3. return {
  4. restrict: 'A',
  5. scope: {
  6. done: '&',
  7. progress: '&'
  8. },
  9. link: function(scope, element, attrs) {
  10. var optionsObj = {
  11. dataType: 'json'
  12. };
  13. if (scope.done) {
  14. optionsObj.done = function() {
  15. scope.$apply(function() {
  16. scope.done({e: e, data: data});
  17. });
  18. };
  19. }
  20. if (scope.progress) {
  21. optionsObj.progress = function(e, data) {
  22. scope.$apply(function() {
  23. scope.progress({e: e, data: data});
  24. });
  25. }
  26. }
  27. // the above could easily be done in a loop, to cover
  28. // all API's that Fileupload provides
  29. element.fileupload(optionsObj);
  30. }
  31. };
  32. });

这些代码是我们能够简单的定义我们的制定。并且制定onDone和onProgress的回调函数。我们使用函数绑定。这样AngularJS一直能正确调用方法和使用正确的变量。

这是因为我们做了独立的作用域声明。它包含了两种绑定:使用是为onprogree另一种是为ondone。

HTML部分代码如下

  1. angular.module('myApp.directives', [])
  2. .directive('datepicker', function() {
  3. return {
  4. // Enforce the angularJS default of restricting the directive to
  5. // attributes only
  6. restrict: 'A',
  7. // Always use along with an ng-model
  8. require: '?ngModel',
  9. scope: {
  10. // This method needs to be defined and
  11. // passed in to the directive from the view controller
  12. select: '&' // Bind the select function we refer to the
  13. // right scope
  14. },
  15. link: function(scope, element, attrs, ngModel) {
  16. if (!ngModel) return;
  17. var optionsObj = {};
  18. optionsObj.dateFormat = 'mm/dd/yy';
  19. var updateModel = function(dateTxt) {
  20. scope.$apply(function () {
  21. // Call the internal AngularJS helper to
  22. // update the two-way binding
  23. ngModel.$setViewValue(dateTxt);
  24. });
  25. };
  26. optionsObj.onSelect = function(dateTxt, picker) {
  27. updateModel(dateTxt);
  28. if (scope.select) {
  29. scope.$apply(function() {
  30. scope.select({date: dateTxt});
  31. });
  32. }
  33. };
  34. ngModel.$render = function() {
  35. // Use the AngularJS internal 'binding-specific' variable
  36. element.datepicker('setDate', ngModel.$viewValue || '');
  37. };
  38. element.datepicker(optionsObj);
  39. }
  40. };
  41. });

controller如下

  1. var app = angular.module('myApp', ['myApp.directives']);
  2. app.controller('MainCtrl', function($scope) {
  3. $scope.uploadFinished = function(e, data) {
  4. console.log('We just finished uploading this baby...');
  5. };
  6. });

【使用Socket.IO】

【与服务器协同与登录】

最后一个例子涵盖了很多内容。大部分与$http资源有关。根据我们的经验。$http服务是AngularJS中核心服务之一。但是他能被拓展去做很多常规web app需求,这包括:

  拥有错误处理链

  能够处理授权和登录跳转。

  不通过JSON与服务器工作

  与外部系统通过jSON工作

所以在这个例子中。我们开发一个完整的应用程序骨架,有这些内容:

1、当错误发生时,跳转到一个统一的错误处理页面。

2、拥有一个ErrorService,能够使指令与视图和控制器之间通信。

3、触发事件,只要服务器返回一个401,这个会被根控制器处理,应用程序级别的根控制器

4、更改请求报文头,增加一些关于当前用户的特定验证信息。

我们不会带大家做整个应用程序,这程序很简单。我们重点说相关步骤。这会很省时间。如果你想复习Server和Factories,回到第七章去。如果你想看着怎么用service,看第5章去。

首先我们看一哈Error Service

  1. var servicesModule = angular.module('myApp.services', []);
  2. servicesModule.factory('errorService', function() {
  3. return {
  4. errorMessage: null,
  5. setError: function(msg) {
  6. this.errorMessage = msg;
  7. },
  8. clear: function() {
  9. this.errorMessage = null;
  10. }
  11. };
  12. });

我们的与Error service独立的错误消息会查找警告消息属性,并且绑定它。并且警告这条消息。

  1. // USAGE: <div alert-bar alertMessage="myMessageVar"></div>
  2. angular.module('myApp.directives', []).
  3. directive('alertBar', ['$parse', function($parse) {
  4. return {
  5. restrict: 'A',
  6. template: '<div class="alert alert-error alert-bar"' +
  7. 'ng-show="errorMessage">' +
  8. '<button type="button" class="close" ng-click="hideAlert()">' +
  9. 'x</button>' +
  10. '{{errorMessage}}</div>',
  11. link: function(scope, elem, attrs) {
  12. var alertMessageAttr = attrs['alertmessage'];
  13. scope.errorMessage = null;
  14. scope.$watch(alertMessageAttr, function(newVal) {
  15. scope.errorMessage = newVal;
  16. });
  17. scope.hideAlert = function() {
  18. scope.errorMessage = null;
  19. // Also clear the error message on the bound variable.
  20. // Do this so that if the same error happens again
  21. // the alert bar will be shown again next time.
  22. $parse(alertMessageAttr).assign(scope, null);
  23. };
  24. }
  25. };
  26. }]);

我们把错误消息加到HTML上。如下

  1. <div alert-bar alertmessage="errorService.errorMessage"></div>

我们需要确认ErrorService在errorService控制器中可用,在我们添加上面的HTML之前。这就是说,如果RootController担任产生AlertBar的功能,那么就有

  1. app.controller('RootController',
  2. ['$scope', 'ErrorService', function($scope, ErrorService) {
  3. $scope.errorService = ErrorService;
  4. });

这样我们就创建好了一个非常好的显示隐藏警告的框架。下面我们看看我们怎么样处理各种服务器返回给我们的各种状态码,通过使用拦截器

  1. servicesModule.config(function ($httpProvider) {
  2. $httpProvider.responseInterceptors.push('errorHttpInterceptor');
  3. });
  4. // register the interceptor as a service
  5. // intercepts ALL angular ajax HTTP calls
  6. servicesModule.factory('errorHttpInterceptor',
  7. function ($q, $location, ErrorService, $rootScope) {
  8. return function (promise) {
  9. return promise.then(function (response) {
  10. return response;
  11. }, function (response) {
  12. if (response.status === 401) {
  13. $rootScope.$broadcast('event:loginRequired');
  14. } else if (response.status >= 400 && response.status < 500) {
  15. ErrorService.setError('Server was unable to find' +
  16. ' what you were looking for... Sorry!!');
  17. }
  18. return $q.reject(response);
  19. });
  20. };
  21. });

现在我们要做的就是

【总结】

至此本书结束。我们毫无保留的尽量全面介绍了AngularJS。我们的目标是使读者能够轻松开发AngularJS程序打下坚实的基础。本书中举了大量实例来解释,并且本书包括大量关于AngularJS的基础知识和一些高级话题

[AngularJS]Chapter 8 秘籍诀窍的更多相关文章

  1. [AngularJS]Chapter 5 与服务器交互

    第八章有关于缓存的东西. [通过$http交互] 传统的AJAX请求如下 var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange ...

  2. [AngularJS]Chapter 3 使用AngularJS构建应用程序

    本章内容提要: 如何布置AngularJS进行快速开发 开启服务器进行测试 使用Karma进行单元测试用例测试 编译压缩AngularJS进行生产 使用Batarang进行Debug 如何简化开发工作 ...

  3. [AngularJS]Chapter 2 剖析安哥拉JS应用程序

    不同于普通的框架,你可以从中选择你想用的方法.在anjular中是不同组件写作工作的.这章中,你会看到anjular中基本的组成部分并且理解他们是如何协同工作的.很多组件会在以后的章节中详细讲解.[开 ...

  4. [AngularJS]Chapter 4 AngularJS程序案例分析

    前边讲的都是基础.本章看看他们怎么合作的. 我们要建一个程序.一次一步.章末结束 [这个程序] GutHub是一个简单的菜谱管理程序.功能是存好吃的的菜谱并提供步骤.这个程序包含: 两列布局 左边是导 ...

  5. [AngularJS]Chapter 1 AnjularJS简介

    创建一个完美的Web应用程序是很令人激动的,但是构建这样应用的复杂度也是不可思议的.我们Angular团队的目标就是去减轻构建这样AJAX应用的复杂度.在谷歌我们经历过各种复杂的应用创建工作比如:GM ...

  6. AngularJS之备忘与诀窍

    译自:<angularjs> 备忘与诀窍 目前为止,之前的章节已经覆盖了Angular所有功能结构中的大多数,包括指令,服务,控制器,资源以及其它内容.但是我们知道有时候仅仅阅读是不够的. ...

  7. Angularjs路由需要了解的那点事

    Angularjs路由需要了解的那点事 我们知道angularjs是特别适合单页面应用,为了通过单页面完成复杂的业务功能,势必需要能够从一个视图跳转到另外一个视图,也就是需要在单个页面里边加载不同的模 ...

  8. AngularJS快速入门指南20:快速参考

    thead>tr>th, table.reference>tbody>tr>th, table.reference>tfoot>tr>th, table ...

  9. AngularJS快速入门指南16:Bootstrap

    thead>tr>th, table.reference>tbody>tr>th, table.reference>tfoot>tr>th, table ...

随机推荐

  1. 工具-vscode使用

    1.智能感知 vscode使用DefinitelyTyped进行自动完成所以需要先安装tsd,命令: npm install -g tsd 安装完成后,首先安装node基本语法支持 tsd query ...

  2. Linux安装vmtools

    unbantu下,先把DVD的Vmwarew.gz,文件拷贝到tmp文件.然后 tar zxf VMware Tools-0....... ls cd ./intall.pl 有个文件,先拷贝到roo ...

  3. Android SQLiteDatabase分析

    Android中的数据存储使用的小巧的SQLite数据库. 为了方便java层使用SQLite,android做了大量的封装.提供了一些列的类和API.本文章就揭露这些封装背后的类图关系. 老规矩,首 ...

  4. EntityFramework 找不到方法:“Void System.Data.Entity.DbModelBuilder.RegisterEntityType

    问题原因,EF当前版本没有该方法,将EF版本升级即可. 1.packages.config <package id="EntityFramework" version=&qu ...

  5. [POJ 1316] 树上的询问

    [题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=1316 [算法] 点分治 由于边权较大,笔者在计算时使用了STL-set 注意当询问为 ...

  6. javascript系列-class12.事件

    1.默认行为          什么是默认行为:默认行为就是浏览器自己触发的事件.比如:a链接的跳转,form提交时的跳转,鼠标右键跳转:   oncontexmenu当点击右键菜单的时候:   re ...

  7. SQL语句之Group By

    1. Group By 语句简介: Group By语句从英文的字面意义上理解就是“根据(by)一定的规则进行分组(Group)”.它的作用是通过一定的规则将一个数据集划分成若干个小的区域,然后针对若 ...

  8. Hessian Spirng实例

    Spring实例 之前,我们做了很简单的纯Hessian的调用,虽然到此已经能够满足远程调用的需求了,但是我听说spring也能够访问hessian的远程服务,研究了一番,废话不多说,直接上示例. 业 ...

  9. Spark编程模型几大要素

    不多说,直接上干货! Spark编程模型几大要素 Driver Program 输入-Transformation-Action 缓存 共享变量

  10. Android 给WebView设置Cookie

    最近项目中用到WebView访问新浪支付页面,有个要求是必须是登录状态,否则会报Token过期,然后我简单的将我从cookie中取得的ticket,即一串数字可以代表用户登录的唯一标识作为参数拼接到u ...