[AngularJS] 1. Angular JS的五大特性

來源:互聯網
上載者:User

 


AngularJS是由Google建立的一種JS架構,使用它可以擴充應用程式中的HTML詞彙,從而在web應用程式中使用HTML聲明動態內容。

AngularJS可以讓你擴充HTML的文法,以便清晰、簡潔地表示應用程式中的組件,並允許將標準的HTML作為你的範本語言,AngularJS可以通過雙向資料繫結自動從擁有JavaScript對 象(模型)的UI(視圖)中同步資料。

 

 

特性一:雙向資料繫結

        資料繫結可能是AngularJS最酷最實用的特性。它能夠協助你避免書寫大量的初始代碼從而節約開發時間。一個典型的web應用可能包含了80%的代碼用來處理,查詢和監聽DOM。資料繫結是的代碼更少,你可以專註於你的應用。

        我們想象一下Model是你的應用中的簡單事實。你的Model是你用來讀取或者更新的部分。資料繫結指令提供了你的Model投射到view的方法。這些投射可以無縫的,毫不影響的應用到web應用中。

        傳統來說,當model變化了。 開發人員需要手動處理DOM元素並且將屬性反映到這些變化中。這個一個雙向的過程。一方面,model變化驅動了DOM中元素變化,另一方面,DOM元素的變化也會影響到Model。這個在使用者互動中更加複雜,因為開發人員需要處理和解析這些互動,然後融合到一個model中,並且更新View。這是一個手動的複雜過程,當一個應用非常龐大的時候,將會是一件非常費勁的事情。

        這裡肯定有更好的解決方案!那就是AngularJS的雙向資料繫結,能夠同步DOM和Model等等。

        這裡有一個非常簡單的例子,用來示範一個input輸入框和<h1>元素的雙向繫結:


[html]
<!doctype html> 
<html ng-app> 
  <head> 
    <script src="http://code.angularjs.org/angular-1.0.0rc10.min.js"></script> 
  </head> 
  <body> 
    <div> 
      <label>Name:</label> 
      <input type="text" ng-model="yourName" placeholder="Enter a name here"> 
      <hr> 
      <h1>Hello, {{yourName || 'World'}}!</h1> 
    </div> 
  </body> 
</html> 

<!doctype html>
<html ng-app>
  <head>
    <script src="http://code.angularjs.org/angular-1.0.0rc10.min.js"></script>
  </head>
  <body>
    <div>
      <label>Name:</label>
      <input type="text" ng-model="yourName" placeholder="Enter a name here">
      <hr>
      <h1>Hello, {{yourName || 'World'}}!</h1>
    </div>
  </body>
</html>


1、標記ng-app告訴AngularJS處理整個HTML頁並引導應用:


[html] 
<html ng-app> 

<html ng-app>2、這行載入AngularJS指令碼:


[html] 
<script src="...angular.js"></script> 

<script src="...angular.js"></script>3、本輸入指令<input ng-model="yourname" />綁定到一個叫yourname的模型變數:


[html] 
<input type="text" ng-model="yourName" placeholder="Enter a name here"> 

<input type="text" ng-model="yourName" placeholder="Enter a name here">4、最後,標籤中的本文是應用的模板,在UI中顯示我們的問候語:


[html] 
<h1>Hello, {{yourName || 'World'}}!</h1> 

<h1>Hello, {{yourName || 'World'}}!</h1>注意,使用雙大括弧標記{{}}的內容是問候語中綁定的運算式

 


特性二:模板

        在AngularJS中,一個模板就是一個HTML檔案。但是HTML的內容擴充了,包含了很多協助你映射model到view的內容。

>> HTML模板將會被瀏覽器解析到DOM中。

>>DOM然後成為AngularJS編譯器的輸入。

>>AngularJS將會遍曆DOM模板來產生一些指導,即,directive(指令)。

>>所有的指令都負責針對view來設定資料繫結。

        我們要理解AuguarJS並不把模板當做String來操作。輸入AngularJS的是DOM而非string。資料繫結是DOM變化,不是字串的串連或者innerHTML變化。使用DOM作為輸入,而不是字串,是AngularJS區別於其它的架構的最大原因。使用DOM允許你擴充指令詞彙並且可以建立你自己的指令,甚至開發可重用的組件。

        最大的好處是為設計師和開發人員建立了一個緊密的工作流程。設計師可以像往常一樣開發標籤,然後開發人員拿過來添加上功能,通過資料繫結將會使得這個過程非常簡單。

        這裡有一個例子,我們使用ng-repeat指令來循環圖表片數組並且加入img模板,如下:


[javascript] 
function AlbumCtrl($scope) { 
    scope.images = [ 
        {"image":"img/image_01.png", "description":"Image 01 description"}, 
        {"image":"img/image_02.png", "description":"Image 02 description"}, 
        {"image":"img/image_03.png", "description":"Image 03 description"}, 
        {"image":"img/image_04.png", "description":"Image 04 description"}, 
        {"image":"img/image_05.png", "description":"Image 05 description"} 
    ]; 

 
<div ng-controller="AlbumCtrl"> 
  <ul> 
    <li ng-repeat="image in images"> 
      <img ng-src="{{image.thumbnail}}" alt="{{image.description}}"> 
    </li> 
  </ul> 
</div> 

    function AlbumCtrl($scope) {
        scope.images = [
            {"image":"img/image_01.png", "description":"Image 01 description"},
            {"image":"img/image_02.png", "description":"Image 02 description"},
            {"image":"img/image_03.png", "description":"Image 03 description"},
            {"image":"img/image_04.png", "description":"Image 04 description"},
            {"image":"img/image_05.png", "description":"Image 05 description"}
        ];
    }

    <div ng-controller="AlbumCtrl">
      <ul>
        <li ng-repeat="image in images">
          <img ng-src="{{image.thumbnail}}" alt="{{image.description}}">
        </li>
      </ul>
    </div>

 

特性三:MVC

        針對用戶端應用開發AngularJS吸收了傳統的MVC基本原則。MVC或者Model-View-Controll設計模式針對不同的人可能意味不同的東西。AngularJS並不執行傳統意義上的MVC,更接近於MVVM(Moodel-View-ViewModel)。

Model
        model是應用中的簡單資料。一般是簡單的javascript對象。這裡沒有必要繼承架構的classes,使用proxy對象封裝或者使用特別的setter/getter方法來訪問。事實上我們處理vanilla javascript的方法就是一個非常好的特性,這種方法使得我們更少使用應用的原型。

ViewModel
        viewmodel是一個用來提供特別資料和方法從而維護指定view的對象。

        viewmodel是$scope的對象,只存在於AnguarJS的應用中。$scope只是一個簡單的js對象,這個對象使用簡單的API來偵測和廣播狀態變化。

Controller
        controller負責設定初始狀態和參數化$scope方法用以控制行為。需要指出的controller並不儲存狀態也不和遠程服務互動。

View
        view是AngularJS解析後渲染和綁定後產生的HTML 。這個部分協助你建立web應用的架構。$scope擁有一個針對資料的參考,controller定義行為,view處理布局和互動。

 


特性四:依賴注入(Dependency Injection,DI)
        AngularJS擁有內建的依賴注入子系統,可以協助開發人員更容易的開發,理解和測試應用。

        DI允許你請求你的依賴,而不是自己找尋它們。比如,我們需要一個東西,DI負責找建立並且提供給我們。

        為了而得到核心的AngularJS服務,只需要添加一個簡單服務作為參數,AngularJS會偵測並且提供給你:

[javascript] 
function EditCtrl($scope, $location, $routeParams) { 
     // Something clever here...  

function EditCtrl($scope, $location, $routeParams) {
     // Something clever here...
}        你也可以定義自己的服務並且讓它們注入:

[javascript]
angular. 
    module('MyServiceModule', []). 
    factory('notify', ['$window', function (win) { 
    return function (msg) { 
        win.alert(msg); 
    }; 
}]); 
  
function myController(scope, notifyService) { 
    scope.callNotify = function (msg) { 
        notifyService(msg); 
    }; 

  
myController.$inject = ['$scope', 'notify']; 

angular.
    module('MyServiceModule', []).
    factory('notify', ['$window', function (win) {
    return function (msg) {
        win.alert(msg);
    };
}]);
 
function myController(scope, notifyService) {
    scope.callNotify = function (msg) {
        notifyService(msg);
    };
}
 
myController.$inject = ['$scope', 'notify'];


特性五:Directives(指令)

        你是不是也希望瀏覽器可以做點兒有意思的事情?那麼AngularJS可以做到。

        指令可以用來建立自訂的標籤。它們可以用來裝飾元素或者操作DOM屬性。

        這裡是一個例子,它監聽一個事件並且針對的更新它的$scope ,如下:

[javascript]
myModule.directive('myComponent', function(mySharedService) { 
    return { 
        restrict: 'E', 
        controller: function($scope, $attrs, mySharedService) { 
            $scope.$on('handleBroadcast', function() { 
                $scope.message = 'Directive: ' + mySharedService.message; 
            }); 
        }, 
        replace: true, 
        template: '<input>' 
    }; 
}); 

myModule.directive('myComponent', function(mySharedService) {
    return {
        restrict: 'E',
        controller: function($scope, $attrs, mySharedService) {
            $scope.$on('handleBroadcast', function() {
                $scope.message = 'Directive: ' + mySharedService.message;
            });
        },
        replace: true,
        template: '<input>'
    };
});
然後,你可以使用這個自訂的directive:

[javascript]
<my-component ng-model="message"></my-component> 

<my-component ng-model="message"></my-component>使用一系列的組件來建立你自己的應用將會讓你更方便的添加,刪除和更新功能。

 

 

額外的特性:測試

AngularJS內含了測試案例可以協助你更方便的執行測試。為什麼不用呢?

JS是一個動態解析性語言,而不是編譯類型的,因此非常的難寫測試。

AngularJS被開成一個可測試的架構。它甚至包含了點對點的單元測試runner。如果你喜歡這個特性,

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.