Home Web Front-end JS Tutorial Detailed explanation of dependency injection mechanism in AngularJS_AngularJS

Detailed explanation of dependency injection mechanism in AngularJS_AngularJS

May 16, 2016 pm 03:54 PM
angularjs dependency injection

Dependency injection is a software design pattern that replaces hard coding of their dependencies within components by giving them in components. This relieves one component, from locating dependencies, to dependency configuration. This helps make components reusable, maintainable and testable.

AngularJS provides a supreme dependency injection mechanism. It provides the following core components that can inject dependencies on each other.

  • Value
  • Factory
  • Service
  • Provider
  • Constant value

Value

Values ​​are simple JavaScript objects that are used to pass values ​​during configuration phase controllers.

//define a module
var mainApp = angular.module("mainApp", []);
//create a value object as "defaultInput" and pass it a data.
mainApp.value("defaultInput", 5);
...
//inject the value in the controller using its name "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);
  }
});

Copy after login

Factory

Factory is used to return the value of the function. It creates value on demand, whenever a service or controller requires it. It usually uses a factory function to calculate and return the corresponding value

//define a module
var mainApp = angular.module("mainApp", []);
//create a factory "MathService" which provides a method multiply to return multiplication of two numbers
mainApp.factory('MathService', function() {   
  var factory = {}; 
  factory.multiply = function(a, b) {
   return a * b 
  }
  return factory;
}); 

//inject the factory "MathService" in a service to utilize the multiply method of factory.
mainApp.service('CalcService', function(MathService){
   this.square = function(a) { 
   return MathService.multiply(a,a); 
  }
});
...

Copy after login

Service

A service is a single JavaScript object that contains a set of functions to perform certain tasks. Services are defined using the service() function, which is then injected into the controller.

//define a module
var mainApp = angular.module("mainApp", []);
...
//create a service which defines a method square to return square of a number.
mainApp.service('CalcService', function(MathService){
   this.square = function(a) { 
   return MathService.multiply(a,a); 
  }
});
//inject the service "CalcService" into the controller
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);
  }
});

Copy after login

Provider

Provider services, factories, etc. used during the configuration phase of the AngularJS internal creation process (corresponding to when AngularJS bootstraps itself). The script mentioned below can be used to create the MathService we have already created earlier. The provider is a special factory method and get() method that returns a value/service/factory.

//define a module
var mainApp = angular.module("mainApp", []);
...
//create a service using provider which defines a method square to return square of a number.
mainApp.config(function($provide) {
  $provide.provider('MathService', function() {
   this.$get = function() {
     var factory = {}; 
     factory.multiply = function(a, b) {
      return a * b; 
     }
     return factory;
   };
  });
});

Copy after login

Constant

Constants are used to account for the fact that values ​​cannot be passed during the configuration phase by configuring them, and values ​​cannot be passed during the configuration phase.

mainApp.constant("configParam", "constant value");

Copy after login

Example

The following example will demonstrate all the above commands.
testAngularJS.html

<html>
<head>
  <title>AngularJS Dependency Injection</title>
</head>
<body>
  <h2>AngularJS Sample Application</h2>
  <div ng-app="mainApp" ng-controller="CalcController">
   <p>Enter a number: <input type="number" ng-model="number" />
   <button ng-click="square()">X<sup>2</sup></button>
   <p>Result: {{result}}</p>
  </div>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/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>

Copy after login

Results

Open textAngularJS.html in your web browser. See the results below.

2015617111816048.jpg (560×240)

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use dependency injection (Dependency Injection) in the Phalcon framework How to use dependency injection (Dependency Injection) in the Phalcon framework Jul 30, 2023 pm 09:03 PM

Introduction to the method of using dependency injection (DependencyInjection) in the Phalcon framework: In modern software development, dependency injection (DependencyInjection) is a common design pattern aimed at improving the maintainability and testability of the code. As a fast and low-cost PHP framework, the Phalcon framework also supports the use of dependency injection to manage and organize application dependencies. This article will introduce you how to use the Phalcon framework

A step-by-step guide to understanding dependency injection in Angular A step-by-step guide to understanding dependency injection in Angular Dec 02, 2022 pm 09:14 PM

This article will take you through dependency injection, introduce the problems that dependency injection solves and its native writing method, and talk about Angular's dependency injection framework. I hope it will be helpful to you!

The latest 5 angularjs tutorials in 2022, from entry to mastery The latest 5 angularjs tutorials in 2022, from entry to mastery Jun 15, 2017 pm 05:50 PM

Javascript is a very unique language. It is unique in terms of the organization of the code, the programming paradigm of the code, and the object-oriented theory. The issue of whether Javascript is an object-oriented language that has been debated for a long time has obviously been There is an answer. However, even though Javascript has been dominant for twenty years, if you want to understand popular frameworks such as jQuery, Angularjs, and even React, just watch the "Black Horse Cloud Classroom JavaScript Advanced Framework Design Video Tutorial".

Dependency injection using JUnit unit testing framework Dependency injection using JUnit unit testing framework Apr 19, 2024 am 08:42 AM

For testing dependency injection using JUnit, the summary is as follows: Use mock objects to create dependencies: @Mock annotation can create mock objects of dependencies. Set test data: The @Before method runs before each test method and is used to set test data. Configure mock behavior: The Mockito.when() method configures the expected behavior of the mock object. Verify results: assertEquals() asserts to check whether the actual results match the expected values. Practical application: You can use a dependency injection framework (such as Spring Framework) to inject dependencies, and verify the correctness of the injection and the normal operation of the code through JUnit unit testing.

Dependency injection pattern in Golang function parameter passing Dependency injection pattern in Golang function parameter passing Apr 14, 2024 am 10:15 AM

In Go, the dependency injection (DI) mode is implemented through function parameter passing, including value passing and pointer passing. In the DI pattern, dependencies are usually passed as pointers to improve decoupling, reduce lock contention, and support testability. By using pointers, the function is decoupled from the concrete implementation because it only depends on the interface type. Pointer passing also reduces the overhead of passing large objects, thereby reducing lock contention. Additionally, DI pattern makes it easy to write unit tests for functions using DI pattern since dependencies can be easily mocked.

Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Jun 27, 2023 pm 07:37 PM

In today's information age, websites have become an important tool for people to obtain information and communicate. A responsive website can adapt to various devices and provide users with a high-quality experience, which has become a hot spot in modern website development. This article will introduce how to use PHP and AngularJS to build a responsive website to provide a high-quality user experience. Introduction to PHP PHP is an open source server-side programming language ideal for web development. PHP has many advantages, such as easy to learn, cross-platform, rich tool library, development efficiency

Dependency injection and service container for PHP functions Dependency injection and service container for PHP functions Apr 27, 2024 pm 01:39 PM

Answer: Dependency injection and service containers in PHP help to flexibly manage dependencies and improve code testability. Dependency injection: Pass dependencies through the container to avoid direct creation within the function, improving flexibility. Service container: stores dependency instances for easy access in the program, further enhancing loose coupling. Practical case: The sample application demonstrates the practical application of dependency injection and service containers, injecting dependencies into the controller, reflecting the advantages of loose coupling.

How to use dependency injection for unit testing in Golang? How to use dependency injection for unit testing in Golang? Jun 02, 2024 pm 08:41 PM

Using dependency injection (DI) in Golang unit testing can isolate the code to be tested, simplifying test setup and maintenance. Popular DI libraries include wire and go-inject, which can generate dependency stubs or mocks for testing. The steps of DI testing include setting dependencies, setting up test cases and asserting results. An example of using DI to test an HTTP request handling function shows how easy it is to isolate and test code without actual dependencies or communication.

See all articles