【AngularJS】—— 7 模塊化

AngularJS有幾大特性,好比:javascript

  1 MVChtml

  2 模塊化java

  3 指令系統app

  4 雙向數據綁定模塊化

那麼本篇就來看看AngularJS的模塊化。函數

  首先先說一下爲何要實現模塊化:單元測試

  1 增長了模塊的可重用性測試

  2 經過定義模塊,實現加載順序的自定義ui

  3 在單元測試中,沒必要加載全部的內容spa

  以前作的幾個例子,控制器的代碼直接寫在script標籤裏面,這樣聲明的函數都是全局的,顯然不是一個最好的選擇。

  下面看看如何進行模塊化:

<script type="text/javascript">
            var myAppModule = angular.module('myApp',[]); myAppModule.filter('test',function(){ return function(name){ return 'hello, '+name+'!'; }; }); myAppModule.controller('myAppCtrl',['$scope',function($scope){ $scope.name='xingoo'; }]); </script>

  首先,經過全局變量angular建立模塊myAppModule

angular.module('myApp',[]);

  第一個參數是綁定的應用app名稱,這個app標識了頁面中angular的入口點,相似main函數的做用。

  第二個參數[]裏面標識了依賴的模塊。

  下面看看如何使用模塊吧!

<!doctype html>
<html ng-app="myApp">
    <head>
         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
         <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
    </head>
    <body>
        <div ng-controller="myAppCtrl"> {{name | test }} </div>
        <script type="text/javascript">
            var myAppModule = angular.module('myApp',[]); myAppModule.filter('test',function(){ return function(name){ return 'hello, '+name+'!'; }; }); myAppModule.controller('myAppCtrl',['$scope',function($scope){ $scope.name='xingoo'; }]); </script>
    </body>
</html>

  直接綁定myApp到ng-app上,就能夠了。

  在script中,咱們經過模塊建立了一個filter和一個控制器。

  filter的做用是 添加字符串修飾。

  控制器的做用則是初始化變量。

  程序的運行結果以下:

相關文章
相關標籤/搜索