2014
Jul
14

AngularJS 是一个 client-side 的 javascript framework,由 Google 工程师开发,并分享出来变成一个 Open Source,Angular Developer 称它为一个 MVW Framework(Model-view-whatever) 而不是平常听到的 MVC,至於什么是 MVW 你就自已看看网址里的解说吧。

Angular 是角的意思,就像三角形的一个角,在 HTML 中就代表「<」这个角符号,那为什么会叫做 Angular 呢? Angular 官网有一段话写著「 AngularJS lets you extend HTML vocabulary for your application」,这句话的意思就是说 Angular 可以自定新的 HTML Tag, Attribute ,一个自定义的 HTML Tag 如

<customize></customize>

我想 Angular 就是因为 HTML 都是使用符号 「< 」开头,因此而命名的吧~

Angular 跟一般的 JS Framework, Jquery , Backbone, YUI, Prototype 有什么不同呢? 我个人试用的感觉是说, Angular 支援了很多功能,但是却不太容易上手,开发架构也跟传统的方式落差很大,加上使用起来没有像 Jquery 这么简单! 所以你在使用 Angular 之前,最好先确定专案是否合适 AngularJS,以免反而适得其反。

AngularJS 最大的特色就是支援 Two Way Data Binding,如果你有看过官网的 Example ,一定会被它 Form - View 同步的功能所吸引住,这也是 Angular 与其它 JS Framework 最大的差别。

另外 AngularJS 支援 Extend HTML Template Engine,透过 Extend 的功能,强化 HTML 基本功能,这样就能将 Javascript 迅速元件化,只要定义好新的 HTML Tag ,那么下一次就能直接重覆使用这些新的 HTML 语法,Angular 将这个功能称作 「directive 」,让你直接在 HTML 上使用新定义的语法,HTML 将会更语义化,更容易让别人看懂你写的程式。

有了 Template Engine ,工程师可以将程式的 Logic 与 view 分开,通常我们会分成 MVC : Model - view - controller 三个部分来实作,AngularJS 也支援这个功能,并且使用 {{ -- }} 的方式来分析 Template , 刚好与 Handlebar 这个 JS Template Engine 一样,如果你刚好有使用 Handlebar ,那么就能够很轻松的转换到 AngularJS 罗。

先来看一个简单的 Demo ,看看 Angular 如何不写 Javascript Code 就能完成 Tab 功能。

View Demo

如何使用 Angular

首先你的程式必需先载入 JQuery 与 AngularJS 这两个 Library,因为 AngularJS 有使用到Jquery 部分功能,所以你必需把 JQuery 放在 AngularJS 前面。

Example
  1. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  2. <script id="angularScript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.15/angular.js"></script>

接著你就可以使用 Angular Template 的功能, 首先我建立一个 input 再加上一个 h1 来绑定这两个 element 之间的数值。

Example
  1. <div ng-app>
  2. <input type="text" ng-model="name" placeholder="Enter a name here">
  3. <h1>Hello {{name}}!</h1>
  4. </div>

以下的 Demo ,是最简单的 Two way data binding ,当你修改 Input 里的数值后,就能够立刻看到页面的变化:


Angular 特色

  • Directives
  • Modules
  • Expression (Template Engine)
官方网站描述 AngularJS 特色如下
For performance and to enable innovation, our goal is that almost every piece of AngularJS should be optional, replaceable, and even used in other non-AngularJS frameworks. You’ll be able to pick and choose the parts you like and write or select others that you like better.

Directives

Angular Directive 可以让你定义新的 Element, Attribute, classname 来执行相对应的 Javascript,例如我可以定义一个新的 element 名称为 ngimage,然后希望这个新的 HTML Tag 输出我指定的 HTML 结构,我希望可以用一个 div 包住一张图片。

  • 我先用 angular.module 宣告一个新的 module
  • 接著用 controller("sample") 宣告一个 controller
  • 最后使用 directive('ngimage') 定义新的 element 名称。

程式范例如下:

Example
  1. <!doctype html>
  2. <html ng-app="myapp">
  3. <head>
  4. <script src="jquery.js"></script>
  5. <script src="angular.js"></script>
  6. <script>
  7.  
  8. angular.module("myapp",[])
  9. .controller("sample", function ($scope) {
  10. $scope.image = "https://angularjs.org/img/AngularJS-small.png";
  11. })
  12. .directive('ngimage', function () {
  13.  
  14. return {
  15. restrict: 'E',
  16. replace: true,
  17. template: '<div><img src="{{image}}"/></div>'
  18. };
  19. });
  20.  
  21. </script>
  22.  
  23. </head>
  24.  
  25. <body ng-controller="sample" >
  26. <ngimage></ngimage>
  27. </body>
  28.  
  29.  
  30. </html>
执行结果
  1. <div><img src="https://angularjs.org/img/AngularJS-small.png"></div>

在这个范例中,我将 Model 资料的部分写在 controller 里,在 $scope 中定义一个 image = "xxx",view 的部分则是定义在 directive 里面 , template: '〈div〉〈img src="{{image}}"/〉〈/div〉' , 当 Angular 看到 ngimage 这个 HTML Tag 之后,就会自动执行 directive 里定义的 function ,并且回传 Compile 过后的 Template ,然后插入至 ngimage element 里,我的程式中有增加一个值 replace: true ,代表 ngimage 会被 template 整个取代。

Modules

AngularJS 支援将 JS 模组化,你可以把每一个功能都写成一个 module ,并可以定义 module 之间的 dependency。

宣告一个 Module 的方式如下 :

Example
  1. var newModule = angular.module("module_name", []);

Dependency

宣告 module 的时候,第二个参数是一个 Array,你可以将会用到的其它 module 设定在这里,例如我有一个功能是做 Tab 切换,而这个功能需要用到核心的 Library 名为 core ,我可以在宣告 angular.module 时,将第二个参数补上 core。

Example
  1. var core = angular.module("core", []);
  2. var tabModule = angular.module("tabModule", ["core"]);

Expression

expression 就是类似 Javascript 的 eval 功能,功能可以包含简单的数学运算,例如 {{3 + 5}} 会输出 8 , 字串的处理 {{"Hello " + " World!"}}。

services

Service 就像是一个包装过的物件,把相关的功能,组合在一起,Angular 中 $ 开头的变数都是一种 service,使用方式跟一般的 Object 相同。

例如 AngularJS 有一个 Service 叫 $http ,它就如同 ajax , curl 等功能,专门用来发送 Request ,使用 $http 时,必需同时宣告接到 response 后的 success function。。

$http 范例
  1. $http({method: 'GET', url: '/xxxx.html'}).
  2. success(function(data, status, headers, config) {
  3. $scope.data = data;
  4. }).
  5. error(function(data, status, headers, config) {
  6. console.log("Got a error from request to xxx.html");
  7. });

其它的 AngularJS Service。

  • $http
  • $httpBackend
  • $log
  • $filter
  • $locale

angularJS 的初始化会在 document ready 的时候执行,所有的 Module 都是这样,如果你有用 JQuery 的 $(document).ready() 这个方式,那么就会遇到 angularJS 与 JQuery 执行先后顺序的问题,只要你先载入 angularJS 这个档案,angularJS 初始化的程序就会在 JQuery document ready 前先执行。

directive tag

angularJS 内建已经提供了好多 directive tag 功能给我们使用,用这些已有的功能,就能快速的建立一个网站。

ng-click

ng-click 提供了滑鼠点击事件处理,有点像 Javascript 的 onclick。

ng-click 使用方式
  1. <a href="" ng-click="angularClick()">anchor</a>

ng-model

ng-model 是实现 two way data binding 的方式,如下的范例, input 里的值可以与 {{name}} 同步化。

ng-model 使用方式
  1. <input ng-model="name" value="text">
  2. {{name}}

ng-show

ng-show 像 if 功能,当某一个值等於 true 时,才显示这段 html 。

ng-show 使用方式
  1. <div ng-show="tab === 1">
  2. tab
  3. </div>
如果要判定 array 是否不是空白,则要使用 ng-show="product.images.length"

ng-hide

ng-hide 的功能跟 ng-show 完成相反,如果判断式成立,则不显示 HTML , angularJS 会自动加上一个 class 「ng-hide」将 HTML 隐藏。

ng-repeat

ng-repeat 就是一个 for loop 功能,

Example
  1. var m = angular.module("myapp", [])
  2. .controller("productList", function ($scope) {
  3. $scope.product = [
  4. {name: "test 1"},
  5. {name: "test 2"}
  6. ];
  7. });
  8.  
  9. <div ng-app="myapp" ng-controller="productList">
  10. <ul ng-repeat="pro in product">
  11. <li>{{pro.name}}</li>
  12. </ul>
  13. </div>

ng-src

如果你想用 angularJS 来显示一张图片,可能会想用这种写法 〈img src="{{image}}"〉,但这是行不通的,因为 browser img tag 会比 angularJS 先执行,所以这种写法,会因为 Browser 无法载入 {{image}} 而出现 error ,必需使用 ng-src 代替。

Example
  1. <img ng-src="{{image}}">

ng-class

ng-class 与 ng-src 存在的原因类似,Browser 也是会对 class 内的名称,加入 CSS Style ,所以必需将 angularJS class 的设定写在 ng-class

Example
  1. <a ng-class="{ active: tab.isSet(1) }">

相关教学


回應 (Leave a comment)