简单教程
提交运行
代码编辑器:
<!DOCTYPE html> <meta charset="utf-8"> <link href="/static/next/css/tryit.css?v=2017082407" rel="stylesheet"/> <script src="https://cdn.staticfile.org/angular.js/1.6.3/angular.min.js"></script> <h1>AngularJS 简单应用</h1> <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> <footer>简单教程,简单编程<br/>Copyright © 简单教程 www.twle.cn</footer> <script> var mainApp = angular.module("mainApp", []); mainApp.config(function($provide) { $provide.provider('MathService', function() { this.$get = function() { var factory = {}; factory.multiply = function(a, b) { return a * b; } return factory; }; }); }); mainApp.value("defaultInput", 5); 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>
运行结果: