AngularJS依赖注入

Posted hello word

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AngularJS依赖注入相关的知识,希望对你有一定的参考价值。

<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://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
      
      <script>
         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;
               };
            });
         });*/
            
         // 创建 value 对象 "defaultInput" 并传递数据
         mainApp.value("defaultInput", 5);
         
         // 创建 factory "MathService" 用于两数的乘积 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;
         });
         
         // 在 service 中注入 factory "MathService"
         mainApp.service(CalcService, function(MathService){
            this.square = function(a) {
               return MathService.multiply(a,a);
            }
         });
         
         // CalcService 和 defaultInput 是前面定义的service和默认值
         mainApp.controller(CalcController, function($scope, CalcService, defaultInput) {
            $scope.number = defaultInput;
            $scope.result = CalcService.square($scope.number);

            // 按钮 ng-click="square" 绑定
            $scope.square = function() {
               $scope.result = CalcService.square($scope.number);
            }
         });
            
      </script>
      
   </body>
</html>

 

以上是关于AngularJS依赖注入的主要内容,如果未能解决你的问题,请参考以下文章

angularjs广播需要注入吗

AngularJS DI(依赖注入)实现推测

AngularJs + typescript 指令依赖注入

2.3了解AngularJS模块和依赖注入

AngularJS简介

AngularJS依赖注入