<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> <script> var mainApp = angular.module('mainApp',[]); // mainApp.config(function ($provide) { // $provide.provider('MathService', function () { // this.$get = function () { // return getValue(); // } // }); // }); var getValue = function () { var factory = {}; factory.multiply = function (a,b) { return a * b; }; factory.addValue = function (a, b) { return a + b; }; console.log(factory); return factory; }; //给一个默认舒适值 mainApp.value('defaultInput', 5); //建立一个工厂,为Service服务 mainApp.factory('MathService', function () { return getValue(); } ); //建立一个服务,等待控制层的调用 mainApp.service('CalcService', function (MathService) { this.square = function (a) { return MathService.multiply(a, a); }; this.add = function (a) { return MathService.addValue(a , a); } }); //控制器,为页面时间服务 mainApp.controller('CalcController', function ($scope, CalcService, defaultInput) { $scope.number = defaultInput; $scope.result = CalcService.square($scope.number); $scope.result1 = CalcService.add($scope.number); $scope.square = function () { $scope.result = CalcService.square($scope.number); $scope.result1 = CalcService.add($scope.number); } }); </script>
<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> <p>结果: {{result1}}</p> </div> </body> </html>
angularJs demo
最新推荐文章于 2024-10-08 09:19:32 发布