angular关于依赖注入

<html>
<head>
  <title>Angular JS Forms</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>
 <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.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) {
      $scope.square = function() {
      $scope.result = CalcService.square($scope.number);
     }
   });
  </script>
</body>
</html>
   <p>Enter a number: <input type="number" ng-model="number" />

构造一个input,使用ng-model进行数据绑定。

 <p>Result: {{result}}</p>

此处输出结果。

  mainApp.factory('MathService', function() {   
     var factory = {}; 
     factory.multiply = function(a, b) {
      return a * b 
     }
     return factory;
   }); 

定义一个工厂,工厂名称为MathService。工厂中定义对象factory,并定义方法multiply。

   mainApp.service('CalcService', function(MathService){
      this.square = function(a) { 
      return MathService.multiply(a,a); 
     }
   });

定义一个服务,名称为CalcService,并且引用工厂中的方法。

 mainApp.controller('CalcController', function($scope, CalcService) {
      $scope.square = function() {
      $scope.result = CalcService.square($scope.number);
     }
   });

定义一个控制器controller,引入$scope和CalcService服务,使用绑定的数据进行数据计算。

至此,一个完整的依赖注入完结。

原文地址:https://www.cnblogs.com/yunzhexiaye/p/6400260.html