案例:AngularJS案例     状态:可编辑再运行    进入竖版
 运行结果 
AخA
         mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
 
1
<html>
2
   
3
   <head>
4
      <meta charset="utf-8">
5
      <title>AngularJS  依赖注入</title>
6
   </head>
7
   
8
   <body>
9
      <h2>AngularJS 简单应用</h2>
10
      
11
      <div ng-app = "mainApp" ng-controller = "CalcController">
12
         <p>输入一个数字: <input type = "number" ng-model = "number" /></p>
13
         <button ng-click = "square()">X<sup>2</sup></button>
14
         <p>结果: {{result}}</p>
15
      </div>
16
      
17
      <script src="/js/angular.js1.4.6/angular.min.js"></script>
18
      
19
      <script>
20
         var mainApp = angular.module("mainApp", []);
21
         
22
         mainApp.config(function($provide) {
23
            $provide.provider('MathService', function() {
24
               this.$get = function() {
25
                  var factory = {};
26
                  
27
                  factory.multiply = function(a, b) {
28
                     return a * b;
29
                  }
30
                  return factory;
31
               };
32
            });
33
         });
34
            
35
         mainApp.value("defaultInput", 5);
36
         
37
         mainApp.factory('MathService', function() {
38
            var factory = {};
39
            
40
            factory.multiply = function(a, b) {
41
               return a * b;
42
            }
43
            return factory;
44
         });
45
         
46
         mainApp.service('CalcService', function(MathService){
47
            this.square = function(a) {
48
               return MathService.multiply(a,a);