<!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 秘籍诀窍的更多相关文章

  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. iOS相册实现与AssetsLibrary框架使用

    概述 在iOS中如果想要获取手机相册里面的图片或者视频的话就要用到系统自带的AssetsLibrary框架,AssetsLibrary.framework中包含以下文件 #import <Ass ...

  2. Java笔试面试题001

    Java笔试面试题之中的一个 1.Struts1中actionform和action属于MVC哪一层,为什么? 解答:actionform和action属于MVC的Model层,Action用来处理业 ...

  3. Tomcat学习之ClassLoader

    Tomcat学习之ClassLoader 2012-09-04 22:19 8993人阅读 评论(4) 收藏 举报  分类: WEB服务器(13)  版权声明:本文为博主原创文章,未经博主允许不得转载 ...

  4. JavaScript的那些坑之变量提升

    想总结一下JS的变量提升特性,都是由于一道题.先上题. var name = 'World!'; (function () { if (typeof name === 'undefined') { v ...

  5. virtual table(有180个评论)

    To implement virtual functions, C++ uses a special form of late binding known as the virtual table. ...

  6. USACO 1.5 Superprime Rib

    Superprime Rib Butchering Farmer John's cows always yields the best prime rib. You can tell prime ri ...

  7. Qt-窗口部件概念介绍

    前言:包括基础窗口部件QWidget.对话框QDialog.QFrame类族 .按钮部件.行编辑器.数值设定框以及滑块部件. 一.基础窗口部件QWidget 窗口部件(Widget)是Qt中建立用户界 ...

  8. Python—使用xm.dom解析xml文件

    什么是DOM? 文件对象模型(Document Object Model,简称DOM),是W3C组织推荐的处理可扩展置标语言的标准编程接口. 一个 DOM 的解析器在解析一个 XML 文档时,一次性读 ...

  9. 利用bat批处理——实现数据库的自动备份和删除

    之前见别人一直在玩批处理,最近公司也在用,就顺便学习下: 首先创建一个 txt文件 命名BackupDataBase  并修改后缀为.bat 编写两条命令: sqlcmd -S . -E -Q &qu ...

  10. 微信小程序面试题

    小程序与原生App哪个好? 答: 小程序除了拥有公众号的低开发成本.低获客成本低以及无需下载等优势,在服务请求延时与用户使用体验是都得到了较大幅度  的提升,使得其能够承载跟复杂的服务功能以及使用户获 ...