如何使用angularjs创建一个简单的计算器?

时间:2015-04-09 10:19:08

标签: angularjs

我可以使用文本框和下拉列表来完成它,但我需要的是使用文本创建计算器,但我无法在文本框中输入按钮值

这是我的index.html

                

  <link data-require="bootstrap-css@3.0.3" data-semver="3.0.3" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" />
  <link href="style.css" rel="stylesheet" />
  <script src="script.js"></script>
</head>
<body>
<h1>Simple Calculator</h1>
<div ng-app="myApp">
    <div ng-controller="calculatorCtrl">

 <div class="offset4 span6 well">
 <label>Enter a value :</label>
 <input ng-model="firstNumber" type="text"> <br/><br>


 <label>Another Value:</label>
 <input ng-model="secondNumber" type="text"> <br/><br>

 <label>Operator:</label>
 <select ng-model="selectedOperator"
 ng-options="operator for operator in operators"></select> 
 <br><br>
            <button ng-model="btn1" class="numberbutton" value="1" ng-click='updateOutput(1)'>1</button>
            <button name="btn2" class="numberbutton" value="2" ng-click='updateOutput(2)'>2</button>
            <button name="btn3" class="numberbutton" value="3" ng-click='updateOutput(3)'>3</button>
             <button name="btn0" class="numberbutton" value="0" ng-click='updateOutput(0)'>0</button>
            <br>

            <button name="btnPlus" class="operationbutton" ng-click='add()'>+</button>
             <button name="btnMinus" class="operationbutton" ng-click='subtract()'>-</button>
             <button name="btnEquals" class="operationbutton" ng-click='calculate()'>=</button>
 <button ng-click="calculate()">Calculate</button> <br><br>

 Result: {{result}}
 </div>
 </div>
</div>
</body>
</html>

我的这里是我的js文件:

的script.js

var myApp = angular.module('myApp', []);

 myApp.controller('calculatorCtrl',function ($scope) {  


$scope.operators = ['+', '-', '*', '/'];
$scope.selectedOperator = $scope.operators[0];



 $scope.updateOutput = function (btn) {
    if ($scope.output == "0" || $scope.newNumber) {
        $scope.output = btn;
        $scope.newNumber = false;
    } else {
        $scope.output += String(btn);
    }
    $scope.pendingValue = toNumber($scope.output);
};

$scope.calculate = function() {
    var A = parseInt($scope.firstNumber);
    var B = parseInt($scope.secondNumber);
    var C = 0;

    switch ($scope.selectedOperator) {
        case '+':
            C = A + B;
            break;
        case '-':
            C = A - B;
            break;
        case '*':
            C = A * B;
            break;
        case '/':
            C = A / B;
            break;                
    }

    $scope.result = C;
}; });

Plnkr:http://plnkr.co/edit/hkjsDJEUTJMFOkdMmgNM?p=preview

2 个答案:

答案 0 :(得分:3)

以下是我将如何做角度风格

控制器:

//代码在这里

var myApp = angular.module('myApp', []);

 myApp.controller('calculatorCtrl',function ($scope) {  

 $scope.txt = '';
 $scope.numbers = [];
 $scope.operators = [];

 $scope.calculate = function() {
    var sum = 0;

    while($scope.operators.length > 0){
      var right = $scope.numbers.pop();
      if(isNaN(right)){
        right = 0;
      }
      var left = $scope.numbers.pop();
      if(isNaN(left)){
        left = 0;
      }

      var op = $scope.operators.pop();
      sum += calc(left,right,op);

    }

    $scope.result = sum;
    $scope.numbers = [];
    $scope.operations = [];
    $scope.txt = '';
};

$scope.addNumber=function(num) { 
    $scope.txt+= num; 
    $scope.numbers.push(parseInt(num));
};

$scope.addOperator = function(operator){
   $scope.txt+= operator;
   $scope.operators.push(operator);
}

 function calc(lhs,rhs,op){
  switch(op){
    case '+':
      return lhs+ rhs;
    case '-':
      return lhs-rhs;

  }
  return 0;
}



});

视图

<h1>Simple Calculator</h1>
<div ng-app="myApp">
<div ng-controller="calculatorCtrl">

<div class="offset4 span6 well">
<label>Enter a value :</label>



<input type="button" value="1" name="no" ng-click="addNumber('1')">  
<input type="button" value="2" name="no" ng-click="addNumber('2')">  
<input type="button" value="3" name="no" ng-click="addNumber('3')"> 
<input type="button" value="0" name="no" ng-click="addNumber('0')">  
<input type="button" value="-" name="no" ng-click="addOperator('-')">  
<input type="button" value="+" name="no" ng-click="addOperator('+')"><br>     <br>
 <button ng-click="calculate()">Calculate</button> <br><br>
 <button ng-click="numbers = []; txt=0;">Clear</button> <br><br>

 Result: {{result}}    </div>
</div>
</div>

答案 1 :(得分:2)

我不确定问题出在哪里,但可能你只是简单地混淆角度 您必须将字符串与数字相关联:firstNumbersecondNumber,因此在按钮上单击您只需要向聚焦文本框模型添加按钮值。

我更改了您的示例,此代码段可能会有所帮助

 var myApp = angular.module('myApp', []);

 myApp.controller('calculatorCtrl', function($scope) {

   function add(x, y) {
     return x + y;
   }

   function sub(x, y) {
     return x - y;
   }

   function mul(x, y) {
     return x * y;
   }

   function div(x, y) {
     return x / y;
   }

   function calc(op, x, y) {
     return $scope.operators[op](parseInt(x, 10), parseInt(y));
   }

   $scope.operators = {
     '+': add,
     '-': sub,
     '*': mul,
     '/': div
   };
   $scope.op = '+';
   $scope.calc = calc;

 });
<script data-require="angular.js@1.4.0-beta.6" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>

<link data-require="bootstrap-css@3.0.3" data-semver="3.0.3" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" />

<h1>Simple Calculator</h1>
<div ng-app="myApp">
  <div ng-controller="calculatorCtrl" ng-init='isNotTBFocused=true'>

    <div class="offset4 span6 well">
      <label>Enter a value :</label>
      <input ng-model="firstNumber" type="text" ng-focus='isNotTBFocused="firstNumber"'>{{(isNotTBFocused==="firstNumber")?'!':''}}
      <br/>
      <br>


      <label>Another Value:</label>
      <input ng-model="secondNumber" type="text" ng-focus='isNotTBFocused="secondNumber"'>{{(isNotTBFocused==="secondNumber")?'!':''}}
      <br/>
      <br>

      <label>Operator:</label>{{ op }}

      <br>
      <br>
      <button ng-repeat="n in [1,2,3,4,5,6,7,8,9,0]" ng-click='$parent[isNotTBFocused]=$parent[isNotTBFocused]+""+n' ng-disabled='isNotTBFocused===true'>{{n}}</button>
      <br>
      <button ng-repeat="(key,val) in operators" ng-click="$parent.op=key" ng-disabled='isNotTBFocused===true'>{{key}}</button>

      <button ng-click="result=calc(op,firstNumber,secondNumber)">=</button>
      <br>
      <br>Result: {{result}}
    </div>
  </div>