angular4.0目前已经发布了,angular是mvw框架,因此对其有一个简单的了解仍是颇有必要的。 目前angular有中文官网,且文档介绍也都是4.x的,可是为了了解其发展过程,咱们先了解anguar1.x版本的,而后再了解4.x版本。css
angular的特色:html
angular1.0版本是在2012年谷歌开源发布的,至今也不过5年的时间,github上的star数已经超过5万,可见其受欢迎程度。ios
首先,咱们先来看一个最简单的angular实例:git
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script> </head> <body> <div ng-app=""> <p>名字 : <input type="text" ng-model="name"></p> <h1>Hello {{name}}</h1> </div> </body> </html>
实例讲解:
当网页加载完毕,AngularJS 自动开启。
ng-app 指令告诉 AngularJS,<div> 元素是 AngularJS 应用程序 的"全部者"。
ng-model 指令把输入域的值绑定到应用程序变量 name,其中能够看到angular也是经过 {{}} 来使用angular表达式的。 angularjs
而且不可贵知一个angular应用是由模块(Module)来定义的,而其又是由 controller 来控制的,后续会主要来说解。github
即咱们首先引入了 angular.min.js ,这个js文件大约有160多kb,仍是能够接受的, 可是相较于vue的70多kb,能够发现angular是vue的将近两倍大小,因此咱们也就常说vue是一个轻型的JavaScript框架。而后使用angular指令 ng-app 指定了div为angular容器。 接着使用了ng-model做为了双向数据绑定的指令,这样,当咱们在input中输入时,就会在下面的H1中获得同步的相应,以此来实现数据的双向绑定(以前提到angular的框架是mvw,即既能够扩展为mvc又能够扩展为mvvm等等)。另外,能够看到这方面angular和vue的理念都是相似的。 web
一、 Angular表达式ajax
即将表达式写在{{}}中,一样也可使用ng-bind实现相同的功能。其中能够是数字、对象、数组等。vue-router
补充:angular初始化。 在angular中,也是能够进行初始化的,使用ng-init便可,这种方法在真正的项目中不经常使用,可是做为演示,仍是有学习的必要的,以下所示:
<div ng-app="" ng-init="quantity=1;cost=5"> <p>总价: {{ quantity * cost }}</p> </div>这样,咱们就经过ng-init将quantity赋值为1,将cost赋值为5了。
二、 Angular指令
angular指令是扩展的html属性,都带有ng-前缀,如以前遇到的ng-init、ng-bind等等。又如能够经过ng-model进行数据绑定。
ng-repeat也能够对数组、对象等遍历,这和vue中的v-for的做用是相似的。
除此以外,angular为了提供更好地可扩展性,还能够经过自定义指令来对应用进行更好地控制。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script> </head> <body ng-app="myApp"> <runoob-directive></runoob-directive> <script> var app = angular.module("myApp", []); app.directive("runoobDirective", function() { return { template : "<h1>自定义指令!</h1>" }; }); </script> </body> </html>
如上所示:经过 app.directive() 方法就能够定义自定义的指令了,而后在html中渲染便可。
在angular中,咱们能够经过如下方式来调用指令:
即这些指令,须要限制使用。 经过添加 restrict 属性,并设置只值为 "A"
, 来设置指令只能经过属性的方式来调用:
var app = angular.module("myApp", []); app.directive("runoobDirective", function() { return { restrict : "A", template : "<h1>自定义指令!</h1>" }; });
另外,咱们还须要知道的是: restrict的值还能够是下面几种:
E --- element
做为元素名使用 A --- attribute
做为属性使用C
--- class做为类名使用
三、 angular模型
所谓模型,实际上就是指ng-model,由于ng-model中的输入域的值能够和angular建立的变量相绑定,以下所示:
<div ng-app="myApp" ng-controller="myCtrl"> 名字: <input ng-model="name"> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.name = "John Doe"; }); </script>
即首先经过module建立一个app,而后加入控制器来控制myCtrl中的内容,controller()的第二个参数接受一个函数,其参数必须为$scope,能够对myCtrl中的值进行控制。
固然,咱们也可使用ng-model实现文章开头举例的数据双向绑定。
angular中还能够对用户输入进行验证, 这是vue自己所缺乏的,以下所示:
<form ng-app="" name="myForm"> Email: <input type="email" name="myAddress" ng-model="text"> <span ng-show="myForm.myAddress.$error.email">不是一个合法的邮箱地址</span> </form>
这里的ng-show和vue中的v-show用法相似,可是这里咱们能够经过经过myForm.myAddress.$error来调用错误,若是这里有错误,那么span就会显示提示错误,若是没有错误,那么就不会显示。 而且其验证的时机就是在失去焦点时开始验证。
咱们还能够根据v-model来获取到表单的状态,包括invalid, dirty, touched, error。
四、angular做用域
使用angular控制器时,咱们可使用做用域$scope了。当在控制器中添加了$scope时,就能够经过视图来获取到做用域中的值了,即获取$scope对象。
另外,全部的应用都有一个根做用域,即$rootScope, 在根做用域中定义的值能够在各个控制器中使用。
五、angular控制器
咱们经过ng-controller来定义控制器,而且能够经过控制器来控制其中的全部数据。
以前咱们举例控制器的时候提到的都是控制属性,实际上还能够经过控制器来实现方法,以下所示:
<div ng-app="myApp" ng-controller="personCtrl"> 名: <input type="text" ng-model="firstName"><br> 姓: <input type="text" ng-model="lastName"><br> <br> 姓名: {{fullName()}} </div> <script> var app = angular.module('myApp', []); app.controller('personCtrl', function($scope) { $scope.firstName = "John"; $scope.lastName = "Doe"; $scope.fullName = function() { return $scope.firstName + " " + $scope.lastName; } }); </script>
这样,就能够在html的表达式中调用方法了。
在大型文件中,控制器中的代码是比较繁琐的,因此咱们每每将之写在一个外部js文件中,而后直接引用便可。
六、angular过滤器
同vue相似,angular也是支持过滤器的,这样,更加方便咱们的操做。使用过滤器很简单,只须要在表达式中添加一个 | 管道字符,而后添加一个过滤器便可。
<div ng-app="myApp" ng-controller="personCtrl"> <p>姓名为 {{ lastName | uppercase }}</p> </div>
如上所示,这个内置的过滤器就会将lastName的内容(能够经过控制器来控制)转化为大写。其余过滤器以下:
<div ng-app="myApp" ng-controller="namesCtrl"> <p><input type="text" ng-model="test"></p> <ul> <li ng-repeat="x in names | filter:test | orderBy:'country'"> {{ (x.name | uppercase) + ', ' + x.country }} </li> </ul> </div>
固然,不少状况下,可能这些过滤仍是不够用的,咱们能够自定义过滤器,以下:
var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.msg = "Runoob"; }); app.filter('reverse', function() { //能够注入依赖 return function(text) { return text.split("").reverse().join(""); } });
即经过filter方法来自定义过滤器。
七、 angularjs服务
在angular中可使用内置服务,也能够自建服务。在angular中服务能够是一个函数或者是一个对象,且共有30多个内置的服务,好比$location服务、$http服务等等。
使用angular中的服务比直接使用window中的对象更好一些,好比使用$location服务比使用window.location更具灵活性。
如上所示,经过对比能够发现使用内置服务是很是不错的。
$http服务也是angular中经常使用的服务,经过$http大大简化了咱们发送ajax请求的步骤,而且还能够很好的和angular相融合。以下所示,就是使用angular的$http服务发送请求:
var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $http) { $http.get("welcome.htm").then(function (response) { $scope.myWelcome = response.data; }); });
能够看到使用$http服务好处以下:
$timeout服务。 此服务对原生的timeout包装了一层函数,实现了promise,在stackoverflow上对此有很好的解释:
var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $timeout) { $scope.myHeader = "Hello World!"; $timeout(function () { $scope.myHeader = "How are you today?"; }, 2000); });
而$interval服务与此相似,不作过多解释。
另外,同指令同样,咱们还能够建立自定义的服务,以下:
app.service('hexafy', function() { this.myFunc = function (x) { return x.toString(16); } });
八、angular HTTP
以前提到angular中内置了不少服务,而其中的http服务即是其中很是重要的一个。 最基本的格式以下:
// 简单的 GET 请求,能够改成 POST $http({ method: 'GET', url: '/someUrl' }).then(function successCallback(response) { // 请求成功执行代码 }, function errorCallback(response) { // 请求失败执行代码 });
可是,通常对于get请求和post请求都会使用相对简洁的形式,以下所示:
$http.get('/someUrl', config).then(successCallback, errorCallback); $http.post('/someUrl', data, config).then(successCallback, errorCallback);
九、angular select(选择框)
angular能够经过数组或者对象建立一个下拉框。
<div ng-app="myApp" ng-controller="myCtrl"> <select ng-init="selectedName = names[0]" ng-model="selectedName" ng-options="x for x in names"> </select> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.names = ["Google", "Runoob", "Taobao"]; }); </script>
即这里使用了ng-options指令。
十、angular 表格
咱们可使用ng-repeat很容易的实现表格,结合使用orderBy过滤器效果更佳。与vue不一样的时,使用Index须要 v-for='item,index in items '这种形式,而angular能够不声明 index 而直接使用$index来引用,可是缺点在于没法解决嵌套的问题,由于当有多个 ng-repeat 时,直接使用$index就会致使数据的混乱。
另外,为了方便表格的使用,angular还提供了了 $odd 和 $even来判断表格中的奇数行和偶数行。
十一、angular html dom
在angular中咱们还能够经过ng-disabled绑定到html中diaabled的属性。 同vue相似,也可使用ng-show、ng-if,只是在angular中多了一个ng-hide,但本质是相似的。
十二、 angular事件
angularjs一样拥有本身的html事件,如使用ng-click来表示点击事件,其余相似。更多的咱们能够在angularjs的API列表中看到。
1三、 angular 模块
在angular中模块定义了一个容器,咱们经过angular.module()来建立模块,而且能够在模块上添加控制器,也能够在模块上添加自定义的过滤器和指令。
即自定义的过滤器、指令都是添加到模块上的。
1四、 表单
和vue相似,在angular中也是可使用v-model来绑定单选框、复选框、下拉菜单等。
1五、 angular.js API
AngularJS 全局 API 用于执行常见任务的 JavaScript 函数集合,如:
以下是常见的api:
举例以下;
<div ng-app="myApp" ng-controller="myCtrl"> <p>{{ x1 }}</p> <p>{{ x2 }}</p> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.x1 = "JOHN"; $scope.x2 = angular.lowercase($scope.x1); }); </script>
1六、 angular bootstrap
angular和bootstrap框架是能够共同使用的,以此来提升开发效率。
以下,咱们只要事先引入bootstrap和angular便可。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="//apps.bdimg.com/libs/bootstrap/3.3.4/css/bootstrap.min.css"> <script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script> </head> <body ng-app="myApp" ng-controller="userCtrl"> <div class="container"> <h3>Users</h3> <table class="table table-striped"> <thead> <tr> <th>编辑</th> <th>名</th> <th>姓</th> </tr> </thead> <tbody> <tr ng-repeat="user in users"> <td> <button class="btn" ng-click="editUser(user.id)"> <span class="glyphicon glyphicon-pencil"></span>编辑 </button> </td> <td>{{ user.fName }}</td> <td>{{ user.lName }}</td> </tr> </tbody> </table> <hr> <button class="btn btn-success" ng-click="editUser('new')"> <span class="glyphicon glyphicon-user"></span>建立新用户 </button> <hr> <h3 ng-show="edit">建立新用户:</h3> <h3 ng-hide="edit">编辑用户:</h3> <form class="form-horizontal"> <div class="form-group"> <label class="col-sm-2 control-label">名:</label> <div class="col-sm-10"> <input type="text" ng-model="fName" ng-disabled="!edit" placeholder="名"> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">姓:</label> <div class="col-sm-10"> <input type="text" ng-model="lName" ng-disabled="!edit" placeholder="姓"> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">密码:</label> <div class="col-sm-10"> <input type="password" ng-model="passw1" placeholder="密码"> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">重复密码:</label> <div class="col-sm-10"> <input type="password" ng-model="passw2" placeholder="重复密码"> </div> </div> </form> <hr> <button class="btn btn-success" ng-disabled="error || incomplete"> <span class="glyphicon glyphicon-save"></span>修改 </button> </div> <script src="myUsers.js"></script> </body> </html>
1七、 angular 包含
使用angular咱们可使用ng-include在html中包含html。
<!DOCTYPE html> <html> <meta charset="utf-8"> <script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script> <body ng-app=""> <div ng-include="'runoob.htm'"></div> </body> </html>
1八、 angular动画
angular提供了动画效果,配合css使用,可是在使用angular动画以前,须要引入 angular-animate.min.js 。而且还要在模型中使用ngAnimate
以下所示:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> div { transition: all linear 0.5s; background-color: lightblue; height: 100px; width: 100%; position: relative; top: 0; left: 0; } .ng-hide { height: 0; width: 0; background-color: transparent; top:-200px; left: 200px; } </style> <script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script> <script src="https://cdn.bootcss.com/angular.js/1.4.6/angular-animate.min.js"></script> </head> <body ng-app="ngAnimate"> <h1>隐藏 DIV: <input type="checkbox" ng-model="myCheck"></h1> <div ng-hide="myCheck"></div> </body> </html>
先引入了angular.min.js又引入了angular-animate.min.js,而后在body中定义了ng-app='ngAnimate',这样就可使用动画了,咱们但愿这个div隐藏,因此使用ng-hide,并配合.ng-hide的css来小时。
值得注意的是咱们在div中添加了transition: all linear 0.5s;。
1九、 angular.js 依赖注入
什么是依赖注入?
wiki 上的解释是:依赖注入(Dependency Injection,简称DI)是一种软件设计模式,在这种模式下,一个或更多的依赖(或服务)被注入(或者经过引用传递)到一个独立的对象(或客户端)中,而后成为了该客户端状态的一部分。该模式分离了客户端依赖自己行为的建立,这使得程序设计变得松耦合,并遵循了依赖反转和单一职责原则。与服务定位器模式造成直接对比的是,它容许客户端了解客户端如何使用该系统找到依赖。
angularjs提供了很好的机制实现依赖注入,以下所示:
value
value是一个简单的JavaScript对象,用于向模块中传递值,而后注入到控制器中。
// 定义一个模块 var mainApp = angular.module("mainApp", []); // 建立 value 对象 "defaultInput" 并传递数据 mainApp.value("defaultInput", 5); ... // 将 "defaultInput" 注入到控制器 mainApp.controller('CalcController', function($scope, CalcService, defaultInput) { $scope.number = defaultInput; $scope.result = CalcService.square($scope.number); $scope.square = function() { $scope.result = CalcService.square($scope.number); } });
即咱们首先定义了一个模块,而后建立了对象defalutInput传递到模块中,紧接着咱们又将模块注入到控制器,而且传入了defaultInput, 因而,咱们就能够在控制器中使用传入的值了。
factory是一个函数,最后返回一个对象,对象中包含方法,而后在service中被调用。 举例以下:
// 定义一个模块 var mainApp = angular.module("mainApp", []); // 建立 factory "MathService" 用于两数的乘积 provides a method multiply to return multiplication of two numbers mainApp.factory('MathService', function() { var factory = {}; factory.multiply = function(a, b) { return a * b } return factory; }); // 在 service 中注入 factory "MathService" mainApp.service('CalcService', function(MathService){ this.square = function(a) { return MathService.multiply(a,a); } }); ...
即定义了factory以后,咱们就能够在service中使用了,而这里的service若是没有猜错就像以前的指令、过滤器同样是自定义的,咱们能够经过 angular.$CalcService()来调用这个方法。
AngularJS 中经过 provider 建立一个 service、factory等(配置阶段)。
Provider 中提供了一个 factory 方法 get(),它用于返回 value/service/factory。
// 定义一个模块 var mainApp = angular.module("mainApp", []); ... // 使用 provider 建立 service 定义一个方法用于计算两数乘积 mainApp.config(function($provide) { $provide.provider('MathService', function() { this.$get = function() { var factory = {}; factory.multiply = function(a, b) { return a * b; } return factory; }; }); });
constant是在配置阶段传递数值的。在配置阶段不可以使用。
20、 angular路由
同vue使用vue-router同样,使用angular路由须要引入angular-route.min.js文件。
<html> <head> <meta charset="utf-8"> <title>AngularJS 路由实例 - 菜鸟教程</title> </head> <body ng-app='routingDemoApp'> <h2>AngularJS 路由应用</h2> <ul> <li><a href="#/">首页</a></li> <li><a href="#/computers">电脑</a></li> <li><a href="#/printers">打印机</a></li> <li><a href="#/blabla">其余</a></li> </ul> <div ng-view></div> <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script> <script src="http://apps.bdimg.com/libs/angular-route/1.3.13/angular-route.js"></script> <script> angular.module('routingDemoApp',['ngRoute']) .config(['$routeProvider', function($routeProvider){ $routeProvider .when('/',{template:'这是首页页面'}) .when('/computers',{template:'这是电脑分类页面'}) .when('/printers',{template:'这是打印机页面'}) .otherwise({redirectTo:'/'}); }]); </script> </body> </html>
基本的路由配置如上,能够看到,这里使用了routerProvider,而后使用when()方法来作出判断,导向不一样的路由。 即在angular中也是使用#/路由路径的方式来进行路由的。另外,在vue中使用router-view来接收路由过来的内容,而在angular中咱们使用的是<div ng-view></div>的方式来接收路由来的内容,基本原理仍是相似的。
更多咱们能够参考这里。