31-依賴注入-2

<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="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>

      <script>
         var mainApp = angular.module("mainApp", []);
         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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章