首页 文章

Angularjs 从 2 输入字段自动计算

提问于
浏览
0

我将计算 2 个输入字段的总和,即价格和数量。我使用 AngularJs 的编程语言包括离子框架。

我的 controller.js

angular.module('starter.controllers', [])

.controller('DashCtrl', function($scope) {
      $scope.a = 0;
      $scope.b = 0;
      $scope.c = $scope.a * $scope.b;
    })

我的 form.html:

<ion-view view-title="Kalkulator">
  <ion-content class="padding">
    <div class="list" ng-controller="DashCtrl">
      <label class="item item-input">
        <span class="input-label">Price</span>
        <input type="text" ng-model="a">
      </label>
      <label class="item item-input">
        <span class="input-label">Qty</span>
        <input type="text" ng-model="b">
      </label>
      <label class="item item-input">
        <span class="input-label">Total</span>
        <input type="text" value="{{ c | currency:'Rp ' }}">
      </label>
    </div>
  </ion-content>
</ion-view>

注意 :
价格= 5000
数量= 2
当我写{{a * b}}时,很可能打印= Rp 10,000.00. 但是我希望在控制器上完成所有过程。

那么,我应该在控制器中写什么脚本来打印正确的结果?

2 回答

  • 0

    使用ng-change指令来观察变化并进行求和

    <ion-view view-title="Kalkulator">
      <ion-content class="padding">
        <div class="list" ng-controller="DashCtrl">
          <label class="item item-input">
            <span class="input-label">Price</span>
            <input type="text" ng-model="a" ng-change="calculate()">
          </label>
          <label class="item item-input">
            <span class="input-label">Qty</span>
            <input type="text" ng-model="b" ng-change="calculate()>
          </label>
          <label class="item item-input">
            <span class="input-label">Total</span>
            <input type="text" value="{{ c | currency:'Rp ' }}">
          </label>
        </div>
      </ion-content>
    </ion-view>
    

    在控制器中

    angular.module('starter.controllers', [])
    
    .controller('DashCtrl', function($scope) {
          $scope.a = 0;
          $scope.b = 0;
          $scope.c = $scope.a * $scope.b;
          $scope.calculate = function(){
              $scope.c = $scope.a * $scope.b
          }
    
        })
    
  • 0

    在'a'和'b'字段输入上使用 ng-keyup 或 ng-change 函数,并在两个 keyup 事件上调用相同的函数,并将此代码放在该函数中。

    $scope.mykeyupfun = function(){$scope.c = $scope.a * $scope.b;}
    

相关问题