<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Demo</title> <script src="js/angular-1.5.8.min.js"></script> </head> <body ng-app="myApp"> <h2>AngularJS简单应用</h2> <div ng-controller="myCtrl"> <p> 输入一个数字:<input type="number" ng-model="number"> <button ng-click="square()">x<sup>2</sup></button> </p> <p>结果:{{result}}</p> </div> <script> var app = angular.module('myApp',[]); //创建value对象,传递数值5 app.value("inputValue",5); app.factory('facService',function () { var factory = {}; factory.multiply = function (a, b) { return a * b; } return factory; }); app.config(function ($provide) {//在应用启动前修改模块配置 $provide.provider('proService',function () { this.$get = function () {//通过$get函数返回内容 var factory = {}; factory.multiply = function (a, b) { return a * b; } return factory; } }); }); app.provider('proService',function () { this.$get = function () {//通过$get函数返回内容 var factory = {}; factory.multiply = function (a, b) { return a * b; } return factory; } }); app.service('serService',function (facService) { this.square = function (a) { return facService.multiply(a,a); } }); //angular中三种声明依赖的方式 /*app.controller('myCtrl',function ($scope,serService,inputValue) { $scope.number = inputValue; $scope.result = serService.square($scope.number); $scope.square = function () { $scope.result = serService.square($scope.number); } });*/ /*app.controller('myCtrl',['$scope','serService','inputValue',function ($scope,serService,inputValue) {//顺序不能乱 $scope.number = inputValue; $scope.result = serService.square($scope.number); $scope.square = function () { $scope.result = serService.square($scope.number); } }]);*/ var MathFn = function ($scope,serService,inputValue) { $scope.number = inputValue; $scope.result = serService.square($scope.number); $scope.square = function () { $scope.result = serService.square($scope.number); } } MathFn.$inject = ['$scope','serService','inputValue']; app.controller('myCtrl',MathFn); </script> </body> </html>