angular學習筆記(二)-建立angular模組

詩&遠方發表於2014-05-06

如果在頁面的html標籤(或任意標籤)中新增ng-app,表示對整個頁面應用angular來管理. 他是一個模組.

模組有助於把東西從全域性名稱空間中隔離.

今天學習如何自定義建立模組:

<!DOCTYPE html>
<html>
<head>
  <title>2.1模組</title>
  <meta charset="utf-8">
  <script src="../angular.js"></script>
  <script src="script.js"></script>
</head>
<body>
  <div ng-app="myApp">
    <div ng-controller="TextController">
      <h1>{{text.message}}</h1>
      <h1>{{text.name}}</h1>
    </div>
  </div>
</body>
</html>
var messages = {};
messages.message = 'hi';
messages.name = 'code_bunny';
var myAppModule = angular.module('myApp',[]);
myAppModule.controller('TextController',function($scope){
    $scope.text = messages;
});



<
div ng-app="myApp">:

  1. ng-app可以加在任何元素上,表示使用這個模組來管理這個元素中的所有內容,

  2. 一個頁面裡只能有一個ng-app,不能有多個,不同的頁面可以運用不同的ng-app模組,但是可以在同一個js裡定義多個模組

  

var messages = {};
messages.message = 'hi';
messages.name = 'code_bunny';

var myAppModule = angular.module('myApp',[]);
myAppModule.controller('TextController',function($scope){
    $scope.text = messages;
});

var otherAppModule = angular.module('otherApp',[]);
otherAppModule.controller('TextController',function($scope){
    $scope.text = messages;
    $scope.text.name = 'white-bunny';
});

 

  3. ng-app="模組名"

      然後在js中使用如下方法來擴充套件模組:     

var myAppModule = angular.module('模組名',[]);

  angular.module()中的第二個引數是必須是一個陣列,用於定義該模組依賴的模組,陣列的值是字串,也就是依賴的模組的名字.一旦寫入了依賴的模組,那麼該模組也就擁有了依賴的模組的指令,方法,等...

  比如常用的ngResource模組:

var HttpREST = angular.module('HttpREST',['ngResource']);

HttpREST.factory('cardResource',function($resource){
    return $resource('/card/user/:userID/:id',{userID:123,id:'@id'},{charge:{method:'POST',params:{charge:true},isArray:false}})
});

在這裡依賴了ngResource模組,就可以使用$resource服務了.(當然需要載入angular-resource.min.js這個檔案)

又比如:

//myRecipe.service模組用來定義服務
var
service = angular.module('myRecipe.service',['ngResource']); service.factory('Recipe',['$resource',function($resource){ return $resource('/recipe/:id',{id:'@id'}); }]); service.factory('loadRecipes',['Recipe','$q',function(Recipe,$q){ return function(){ ... } }]); service.factory('loadRecipe',['Recipe','$q','$route','$routeParams',function(Recipe,$q,$route,$routeParams){ return function(){ ... } }]);
//myRecipe.directive模組用來定義指令
var
directive = angular.module('myRecipe.directive',[]); directive.directive('focus',function(){ return { ... } }); directive.directive('loading',['$rootScope',function($rootScope){ return { ... } }]);
//在myRecipe中就可以使用myRecipe.service和myRecipe.directive裡面的服務和指令了.
var app = angular.module('myRecipe',['myRecipe.service','myRecipe.directive']);

 

  4. 可以在自己擴充套件的模組下新增控制器: 

myAppModule.controller('TextController',function($scope){
    ...
});

   

$scope.text = messages;

text是$scope作用域下的一個物件,但是message卻是一個外部的物件,使用這種方式來定義作用於下的物件,而不是直接在作用域中宣告,這樣,同一個變數,可以在多個模組或多個控制器中被使用



相關程式碼託管:

https://github.com/OOP-Code-Bunny/angular



  

相關文章