之前看到一个试题,要求用angularJs和Bootstrap写一个简单的计算器,通过百度,发现没有什么好的例子,所以呢,我就把自己写的一个例子发出来给大家。(大牛勿喷)
HTML代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>计算器</title> <link type="text/css" href="https://www.jb51.net/css/bootstrap.min.css"/> <link type="text/css" href="https://www.jb51.net/css/style.css" /> </head> <body> <div ng-app="myApp" ng-controller="myController"> <div></div> <div> <div> <div> <input type="text" ng-model="shuzi" value="{{shuzi}}" disabled/> <input type="text" ng-model="jieguo" value="{{jieguo}}" disabled/> </div> <br /> <div> <div> <button type="button" ng-click="num(7)">7</button> <button type="button" ng-click="num(8)">8</button> <button type="button" ng-click="num(9)">9</button> <button type="button" ng-click="num('https://www.jb51.net/')">÷</button> <br/> <button type="button" ng-click="num(4)">4</button> <button type="button" ng-click="num(5)">5</button> <button type="button" ng-click="num(6)">6</button> <button type="button" ng-click="num('*')">x</button> <br/> <button type="button" ng-click="num(1)">1</button> <button type="button" ng-click="num(2)">2</button> <button type="button" ng-click="num(3)">3</button> <button type="button" ng-click="num('-')">-</button> <br/> <button type="button" ng-click="num(0)">0</button> <button type="button" ng-click="reversal()">±</button> <button type="button" ng-click="num('.')">.</button> <button type="button" ng-click="num('+')">+</button> </div> <div> <button type="button" ng-click="remove()">清零</button> <br/> <button type="button" ng-click="js()">=</button> </div> </div> </div> </div> <div></div> </div> </body> <script type="text/javascript" src="https://www.jb51.net/js/angular.1.6.3.js"></script> <script type="text/javascript" src="https://www.jb51.net/js/bootstrap.min.js"></script> <script type="text/javascript" src="https://www.jb51.net/js/jisuanqi.js"></script> </html>
AngularJs代码:
var myApp=angular.module("myApp",[]); myApp.controller("myController",function($scope){ $scope.shuzi=""; $scope.jieguo=0; $scope.num=function(num){ $scope.shuzi+=num; } $scope.js=function(){ $scope.jieguo=(eval($scope.shuzi)); } $scope.reversal=function(){ if(eval($scope.shuzi)>0){ $scope.shuzi="-"+$scope.shuzi; }else{ $scope.shuzi=$scope.shuzi.substring(1); } } $scope.remove=function(){ $scope.shuzi=""; $scope.jieguo=0; } })
效果图展示: