1.AngularJS 模組

來源:互聯網
上載者:User

標籤:部分   依賴   模組   span   空間   control   []   元素   應用   

上一章講的資料繫結,是把控制器的代碼寫到一個全域命名空間中定義的函數裡:

function MyController($scope) {var updateClock = function() {$scope.clock = new Date();};setInterval(function() {$scope.$apply(updateClock);}, 1000);updateClock();};

  

在AngularJS 中,模組是定義應用的主要方式,包含了主要的應用代碼。一個應用可以包含多個模組,每個模組包含具體的代碼。使用模組有許多好處,比如:

  • 保持全域命名空間的清潔
  • 測試更容易找到相互隔離的功能
  • 可以在不同的應用之間複用代碼
  • 是應用能夠以任意順序載入代碼的各個部分

我們使用angular.module() 方法來聲明模組,這個方法接受兩個參數,第一個是模組的名稱,第二個是依賴列表,中括弧[]表示該模組沒有依賴,如果有依賴的話會在中括弧寫上依賴的模組名字。

angular.module(‘myApp‘, []) 方法相當於AngularJS 模組的setter 方法,用來定義模組。

angular.module(‘myApp‘)  方法只傳遞一個參數,相當於getter 方法,用來引用模組。

開發大型應用時,會建立多個模組類承載商務邏輯。將複雜的功能分割成不同的模組,有助於單獨為它們編寫測試。

1.建立模組

<div ng-app="myApp">...</div><script><!--通過angular.module 函數建立模組-->var app = angular.module("myApp", []); </script>

  

2.添加控制器

<!--使用ng-controller 指令添加控制器--><div ng-app="myApp" ng-controller="myCtrl">{{ firstName + " " + lastName }}</div><script>var app = angular.module("myApp", []);app.controller("myCtrl", function($scope) {    $scope.firstName = "John";    $scope.lastName = "Doe";});</script>

  

3.添加指令

AngularJS 提供了很多內建的指令,可以用它們來為你的應用添加功能。

<div ng-app="myApp" runoob-directive></div><script>var app = angular.module("myApp", []);<!--用模組為應用添加自己的指令-->app.directive("runoobDirective", function() {    return {        template : "我在指令構造器中建立!"    };});</script>

  

4.模組和控制器包含在JS檔案中

通常AngularJS應用程式將模組和控制器包含在js檔案中。

<!DOCTYPE html><html><script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script><body><div ng-app="myApp" ng-controller="myCtrl">{{ firstName + " " + lastName }}</div><!--myApp.js 包含了應用模組的定義程式--><script src="myApp.js"></script><!--myCtrl.js 包含了控制器--><script src="myCtrl.js"></script></body></html>

  

5.什麼時候載入angular.js

對於HTML應用程式,通常建議吧所有的指令碼都放置在<body> 元素的最底部。

這回提高網頁載入速度,應為HTML載入不受制於指令碼載入。

AngularJS 的庫檔案是在<head>標籤裡載入的,因為對angular.module 的調用只能在庫載入完成後才能進行。

另外也可以在<body>元素中載入,但是必須放在AngularJS指令碼前面。

 

1.AngularJS 模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.