AngularJS 依賴注入

來源:互聯網
上載者:User

標籤:

什麼是依賴注入

wiki 上的解釋是:依賴注入(Dependency Injection,簡稱DI)是一種軟體設計模式,在這種模式下,一個或更多的依賴(或服務)被注入(或者通過引用傳遞)到一個獨立的對象(或用戶端)中,然後成為了該用戶端狀態的一部分。

該模式分離了用戶端依賴本身行為的建立,這使得程式設計變得松耦合,並遵循了依賴反轉和單一職責原則。與服務定位器模式形成直接對比的是,它允許用戶端瞭解用戶端如何使用該系統找到依賴

一句話 --- 沒事你不要來找我,有事我會去找你。

AngularJS 提供很好的依賴注入機制。以下5個核心組件用來作為依賴注入:

  • value
  • factory
  • service
  • provider
  • constant
value

Value 是一個簡單的 javascript 對象,用於向控制器傳遞值(設定階段):

// 定義一個模組var mainApp = angular.module("mainApp", []);// 建立 value 對象 "defaultInput" 並傳遞資料mainApp.value("defaultInput", 5);...// 將 "defaultInput" 注入到控制器mainApp.controller(‘CalcController‘, function($scope, CalcService, defaultInput) {   $scope.number = defaultInput;   $scope.result = CalcService.square($scope.number);      $scope.square = function() {      $scope.result = CalcService.square($scope.number);   }});
factory

factory 是一個函數用於傳回值。在 service 和 controller 需要時建立。

通常我們使用 factory 函數來計算或傳回值。

// 定義一個模組var mainApp = angular.module("mainApp", []);// 建立 factory "MathService" 用於兩數的乘積 provides a method multiply to return multiplication of two numbersmainApp.factory(‘MathService‘, function() {   var factory = {};      factory.multiply = function(a, b) {      return a * b   }   return factory;}); // 在 service 中注入 factory "MathService"mainApp.service(‘CalcService‘, function(MathService){   this.square = function(a) {      return MathService.multiply(a,a);   }});...
provider

AngularJS 中通過 provider 建立一個 service、factory等(設定階段)。

Provider 中提供了一個 factory 方法 get(),它用於返回 value/service/factory。

// 定義一個模組var mainApp = angular.module("mainApp", []);...// 使用 provider 建立 service 定義一個方法用於計算兩數乘積mainApp.config(function($provide) {   $provide.provider(‘MathService‘, function() {      this.$get = function() {         var factory = {};                    factory.multiply = function(a, b) {            return a * b;          }         return factory;      };   });});
constant

constant(常量)用來在設定階段傳遞數值,注意這個常量在設定階段是停用。

mainApp.constant("configParam", "constant value");
執行個體

以下執行個體提供了以上幾個依賴注入機制的示範。

<html>    <head>        <meta charset="utf-8">        <title>AngularJS 依賴注入</title>    </head>    <body>        <h2>AngularJS 簡單應用</h2>        <div ng-app="mainApp" ng-controller="CalcController">            <p>輸入一個數字: <input type="number" ng-model="number" /></p>            <button ng-click="square()">X<sup>2</sup></button>            <p>結果: {{result}}</p>        </div>        <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>        <script>            var mainApp = angular.module("mainApp", []);            mainApp.config(function($provide) {                $provide.provider(‘MathService‘, function() {                    this.$get = function() {                        var factory = {};                        factory.multiply = function(a, b) {                            return a * b;                        }                        return factory;                    };                });            });            mainApp.value("defaultInput", 5);            mainApp.factory(‘MathService‘, function() {                var factory = {};                factory.multiply = function(a, b) {                    return a * b;                }                return factory;            });            mainApp.service(‘CalcService‘, function(MathService) {                this.square = function(a) {                    return MathService.multiply(a, a);                }            });            mainApp.controller(‘CalcController‘, function($scope, CalcService, defaultInput) {                $scope.number = defaultInput;                $scope.result = CalcService.square($scope.number);                $scope.square = function() {                    $scope.result = CalcService.square($scope.number);                }            });        </script>    </body></html>

 

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.