[AngularJS]Chapter 8 秘籍诀窍
- <!DOCTYPE html>
- <html ng-app="myApp">
- <head lang="en">
- <meta charset="utf-8">
- <title>File Upload with AngularJS</title>
- <!-- Because we are loading jQuery before AngularJS,
- Angular will use the jQuery library instead of
- its own jQueryLite implementation -->
- <script
- src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
- </script>
- <script
- src="http://raw.github.com/blueimp/jQuery-File-Upload/master/js/vendor/
- jquery.ui.widget.js">
- </script>
- <script
- src="http://raw.github.com/blueimp/jQuery-File-Upload/master/js/
- jquery.iframe-transport.js">
- </script>
- <script
- src="http://raw.github.com/blueimp/jQuery-File-Upload/master/js/
- jquery.fileupload.js">
- </script>
- <script
- src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js">
- </script>
- <script src="app.js"></script>
- </head>
- <body ng-controller="MainCtrl">
- File Upload:
- <!-- We will define uploadFinished in MainCtrl and attach
- it to the scope, so that it is available here -->
- <input id="testUpload"
- type="file"
- fileupload
- name="files[]"
- data-url="/server/uploadFile"
- multiple
- done="uploadFinished(e, data)">
- </body>
- </html>
到现在为止。我们已经件讲述了AngularJS的绝大部分内容。包括指令,服务,控制器,资源等等。但是我们也知道只看不实践是不行的。有时我们并不关心Angular是怎样工作的。我们只是想知道怎么才能让它工作。
这本本章中。我们会通过给出完整例子,来说明常见问题。
这些例子包括
1、使用jQuery Datepicker
2、Teams List应用:控制器和过滤器的通讯
3、AngularJS中的文件上传
4、私用socket.io
5、使用服务(Servers)
【使用jQuery Datepicker】
源码在github中可见
我们想这样定义我们的datepicker组件
- <input datepicker ng-model="currentDate" select="updateMyText(date)"></input>
js这样写
代码很简单。我们来看看特殊的部分。
ng-model
绑定选择事件
调用选择事件
【本例的其他部分】
- var app = angular.module('myApp', ['myApp.directives']);
- app.controller('MainCtrl', function($scope) {
- $scope.myText = 'Not Selected';
- $scope.currentDate = '';
- $scope.updateMyText = function(date) {
- $scope.myText = 'Selected';
- };
- });
HTML部分
- <!DOCTYPE html>
- <html ng-app="myApp">
- <head lang="en">
- <meta charset="utf-8">
- <title>AngularJS Datepicker</title>
- <script
- src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
- </script>
- <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js">
- </script>
- <script
- src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/
- angular.min.js">
- </script>
- <link rel="stylesheet"
- href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
- <script src="datepicker.js"></script>
- <script src="app.js"></script>
- </head>
- <body ng-controller="MainCtrl">
- <input id="dateField"
- datepicker
- ng-model="$parent.currentDate"
- select="updateMyText(date)">
- <br/>
- {{myText}} - {{currentDate}}
- </body>
- </html>
【团队列表APP:过滤器和控制器的通信】
【AngularJS中的文件上传】
另一个常见的用法师上传文件。虽然我们可以通过input type=file来实现,但是。我们现在将要拓展文件上传解决方案。比较好的一个是BlueImp’s File Upload,他使用jQuery和jQueryUI。它的api非常简单
代码如下
- angular.module('myApp.directives', [])
- .directive('fileupload', function() {
- return {
- restrict: 'A',
- scope: {
- done: '&',
- progress: '&'
- },
- link: function(scope, element, attrs) {
- var optionsObj = {
- dataType: 'json'
- };
- if (scope.done) {
- optionsObj.done = function() {
- scope.$apply(function() {
- scope.done({e: e, data: data});
- });
- };
- }
- if (scope.progress) {
- optionsObj.progress = function(e, data) {
- scope.$apply(function() {
- scope.progress({e: e, data: data});
- });
- }
- }
- // the above could easily be done in a loop, to cover
- // all API's that Fileupload provides
- element.fileupload(optionsObj);
- }
- };
- });
这些代码是我们能够简单的定义我们的制定。并且制定onDone和onProgress的回调函数。我们使用函数绑定。这样AngularJS一直能正确调用方法和使用正确的变量。
这是因为我们做了独立的作用域声明。它包含了两种绑定:使用是为onprogree另一种是为ondone。
HTML部分代码如下
- angular.module('myApp.directives', [])
- .directive('datepicker', function() {
- return {
- // Enforce the angularJS default of restricting the directive to
- // attributes only
- restrict: 'A',
- // Always use along with an ng-model
- require: '?ngModel',
- scope: {
- // This method needs to be defined and
- // passed in to the directive from the view controller
- select: '&' // Bind the select function we refer to the
- // right scope
- },
- link: function(scope, element, attrs, ngModel) {
- if (!ngModel) return;
- var optionsObj = {};
- optionsObj.dateFormat = 'mm/dd/yy';
- var updateModel = function(dateTxt) {
- scope.$apply(function () {
- // Call the internal AngularJS helper to
- // update the two-way binding
- ngModel.$setViewValue(dateTxt);
- });
- };
- optionsObj.onSelect = function(dateTxt, picker) {
- updateModel(dateTxt);
- if (scope.select) {
- scope.$apply(function() {
- scope.select({date: dateTxt});
- });
- }
- };
- ngModel.$render = function() {
- // Use the AngularJS internal 'binding-specific' variable
- element.datepicker('setDate', ngModel.$viewValue || '');
- };
- element.datepicker(optionsObj);
- }
- };
- });
controller如下
- var app = angular.module('myApp', ['myApp.directives']);
- app.controller('MainCtrl', function($scope) {
- $scope.uploadFinished = function(e, data) {
- console.log('We just finished uploading this baby...');
- };
- });
【使用Socket.IO】
【与服务器协同与登录】
最后一个例子涵盖了很多内容。大部分与$http资源有关。根据我们的经验。$http服务是AngularJS中核心服务之一。但是他能被拓展去做很多常规web app需求,这包括:
拥有错误处理链
能够处理授权和登录跳转。
不通过JSON与服务器工作
与外部系统通过jSON工作
所以在这个例子中。我们开发一个完整的应用程序骨架,有这些内容:
1、当错误发生时,跳转到一个统一的错误处理页面。
2、拥有一个ErrorService,能够使指令与视图和控制器之间通信。
3、触发事件,只要服务器返回一个401,这个会被根控制器处理,应用程序级别的根控制器
4、更改请求报文头,增加一些关于当前用户的特定验证信息。
我们不会带大家做整个应用程序,这程序很简单。我们重点说相关步骤。这会很省时间。如果你想复习Server和Factories,回到第七章去。如果你想看着怎么用service,看第5章去。
首先我们看一哈Error Service
- var servicesModule = angular.module('myApp.services', []);
- servicesModule.factory('errorService', function() {
- return {
- errorMessage: null,
- setError: function(msg) {
- this.errorMessage = msg;
- },
- clear: function() {
- this.errorMessage = null;
- }
- };
- });
我们的与Error service独立的错误消息会查找警告消息属性,并且绑定它。并且警告这条消息。
- // USAGE: <div alert-bar alertMessage="myMessageVar"></div>
- angular.module('myApp.directives', []).
- directive('alertBar', ['$parse', function($parse) {
- return {
- restrict: 'A',
- template: '<div class="alert alert-error alert-bar"' +
- 'ng-show="errorMessage">' +
- '<button type="button" class="close" ng-click="hideAlert()">' +
- 'x</button>' +
- '{{errorMessage}}</div>',
- link: function(scope, elem, attrs) {
- var alertMessageAttr = attrs['alertmessage'];
- scope.errorMessage = null;
- scope.$watch(alertMessageAttr, function(newVal) {
- scope.errorMessage = newVal;
- });
- scope.hideAlert = function() {
- scope.errorMessage = null;
- // Also clear the error message on the bound variable.
- // Do this so that if the same error happens again
- // the alert bar will be shown again next time.
- $parse(alertMessageAttr).assign(scope, null);
- };
- }
- };
- }]);
我们把错误消息加到HTML上。如下
- <div alert-bar alertmessage="errorService.errorMessage"></div>
我们需要确认ErrorService在errorService控制器中可用,在我们添加上面的HTML之前。这就是说,如果RootController担任产生AlertBar的功能,那么就有
- app.controller('RootController',
- ['$scope', 'ErrorService', function($scope, ErrorService) {
- $scope.errorService = ErrorService;
- });
这样我们就创建好了一个非常好的显示隐藏警告的框架。下面我们看看我们怎么样处理各种服务器返回给我们的各种状态码,通过使用拦截器
- servicesModule.config(function ($httpProvider) {
- $httpProvider.responseInterceptors.push('errorHttpInterceptor');
- });
- // register the interceptor as a service
- // intercepts ALL angular ajax HTTP calls
- servicesModule.factory('errorHttpInterceptor',
- function ($q, $location, ErrorService, $rootScope) {
- return function (promise) {
- return promise.then(function (response) {
- return response;
- }, function (response) {
- if (response.status === 401) {
- $rootScope.$broadcast('event:loginRequired');
- } else if (response.status >= 400 && response.status < 500) {
- ErrorService.setError('Server was unable to find' +
- ' what you were looking for... Sorry!!');
- }
- return $q.reject(response);
- });
- };
- });
现在我们要做的就是
【总结】
至此本书结束。我们毫无保留的尽量全面介绍了AngularJS。我们的目标是使读者能够轻松开发AngularJS程序打下坚实的基础。本书中举了大量实例来解释,并且本书包括大量关于AngularJS的基础知识和一些高级话题
[AngularJS]Chapter 8 秘籍诀窍的更多相关文章
- [AngularJS]Chapter 5 与服务器交互
第八章有关于缓存的东西. [通过$http交互] 传统的AJAX请求如下 var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange ...
- [AngularJS]Chapter 3 使用AngularJS构建应用程序
本章内容提要: 如何布置AngularJS进行快速开发 开启服务器进行测试 使用Karma进行单元测试用例测试 编译压缩AngularJS进行生产 使用Batarang进行Debug 如何简化开发工作 ...
- [AngularJS]Chapter 2 剖析安哥拉JS应用程序
不同于普通的框架,你可以从中选择你想用的方法.在anjular中是不同组件写作工作的.这章中,你会看到anjular中基本的组成部分并且理解他们是如何协同工作的.很多组件会在以后的章节中详细讲解.[开 ...
- [AngularJS]Chapter 4 AngularJS程序案例分析
前边讲的都是基础.本章看看他们怎么合作的. 我们要建一个程序.一次一步.章末结束 [这个程序] GutHub是一个简单的菜谱管理程序.功能是存好吃的的菜谱并提供步骤.这个程序包含: 两列布局 左边是导 ...
- [AngularJS]Chapter 1 AnjularJS简介
创建一个完美的Web应用程序是很令人激动的,但是构建这样应用的复杂度也是不可思议的.我们Angular团队的目标就是去减轻构建这样AJAX应用的复杂度.在谷歌我们经历过各种复杂的应用创建工作比如:GM ...
- AngularJS之备忘与诀窍
译自:<angularjs> 备忘与诀窍 目前为止,之前的章节已经覆盖了Angular所有功能结构中的大多数,包括指令,服务,控制器,资源以及其它内容.但是我们知道有时候仅仅阅读是不够的. ...
- Angularjs路由需要了解的那点事
Angularjs路由需要了解的那点事 我们知道angularjs是特别适合单页面应用,为了通过单页面完成复杂的业务功能,势必需要能够从一个视图跳转到另外一个视图,也就是需要在单个页面里边加载不同的模 ...
- AngularJS快速入门指南20:快速参考
thead>tr>th, table.reference>tbody>tr>th, table.reference>tfoot>tr>th, table ...
- AngularJS快速入门指南16:Bootstrap
thead>tr>th, table.reference>tbody>tr>th, table.reference>tfoot>tr>th, table ...
随机推荐
- 工具-vscode使用
1.智能感知 vscode使用DefinitelyTyped进行自动完成所以需要先安装tsd,命令: npm install -g tsd 安装完成后,首先安装node基本语法支持 tsd query ...
- Linux安装vmtools
unbantu下,先把DVD的Vmwarew.gz,文件拷贝到tmp文件.然后 tar zxf VMware Tools-0....... ls cd ./intall.pl 有个文件,先拷贝到roo ...
- Android SQLiteDatabase分析
Android中的数据存储使用的小巧的SQLite数据库. 为了方便java层使用SQLite,android做了大量的封装.提供了一些列的类和API.本文章就揭露这些封装背后的类图关系. 老规矩,首 ...
- EntityFramework 找不到方法:“Void System.Data.Entity.DbModelBuilder.RegisterEntityType
问题原因,EF当前版本没有该方法,将EF版本升级即可. 1.packages.config <package id="EntityFramework" version=&qu ...
- [POJ 1316] 树上的询问
[题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=1316 [算法] 点分治 由于边权较大,笔者在计算时使用了STL-set 注意当询问为 ...
- javascript系列-class12.事件
1.默认行为 什么是默认行为:默认行为就是浏览器自己触发的事件.比如:a链接的跳转,form提交时的跳转,鼠标右键跳转: oncontexmenu当点击右键菜单的时候: re ...
- SQL语句之Group By
1. Group By 语句简介: Group By语句从英文的字面意义上理解就是“根据(by)一定的规则进行分组(Group)”.它的作用是通过一定的规则将一个数据集划分成若干个小的区域,然后针对若 ...
- Hessian Spirng实例
Spring实例 之前,我们做了很简单的纯Hessian的调用,虽然到此已经能够满足远程调用的需求了,但是我听说spring也能够访问hessian的远程服务,研究了一番,废话不多说,直接上示例. 业 ...
- Spark编程模型几大要素
不多说,直接上干货! Spark编程模型几大要素 Driver Program 输入-Transformation-Action 缓存 共享变量
- Android 给WebView设置Cookie
最近项目中用到WebView访问新浪支付页面,有个要求是必须是登录状态,否则会报Token过期,然后我简单的将我从cookie中取得的ticket,即一串数字可以代表用户登录的唯一标识作为参数拼接到u ...