angularjs输入填充问题

时间:2017-07-04 16:43:35

标签: javascript angularjs

尝试制作一个简单的计算器,但有一些问题。 所以我不能通过键盘填充输入值,我也有两个错误([ngModel:nonassign]当我加载页面,当我试图通过键盘填充输入值 -

  

这个。$$ ngModelSet不是函数

我希望有人可以帮助我。

<div class="container" ng-controller="calcCtrl">
    <div class="content">
    <br><br><br>
    <input type="text" ng-model="formula.join('')" ></input>
    <br><br><span class="content_tab tab"></span> <br>
    <button  ng-click='add(7)'>7</button>
    <button  ng-click='add(8)'>8</button>
    <button  ng-click='add(9)'>9</button>
    <button  ng-click='add("/")'>/</button>
    <br>
    <button  ng-click='add(4)'>4</button>
    <button ng-click='add(5)'>5</button>
    <button  ng-click='add(6)'>6</button>
    <button  ng-click='add("*")'>*</button>
    <br>
    <button  ng-click='add(1)'>1</button></td>
    <button  ng-click='add(2)'>2</button></td>
    <button  ng-click='add(3)'>3</button></td>
    <button  ng-click='add("-")'>-</button></td>
    <br>
    <button  ng-click='add(0)'>0</button>
    <button  ng-click='add(".")'>.</button>
    <td rowspan='2'><button  ng-click='add("+")'>+</button>
    <button ng-click="eval()">=</button>
    <br>
    <button  ng-click="remove()">CLEAR</button>
</div>

app.controller('calcCtrl',  function($scope) {
    $scope.formula = ['0'];
    $scope.add = function(item) {
    if ($scope.formula == '0') $scope.formula = [item];
    else $scope.formula.push(item);
};
    $scope.remove = function() {
    $scope.formula.pop();
    if($scope.formula.length == 0) $scope.formula = ['0'];
};
    $scope.eval = function() {
    var result = eval($scope.formula.join(''));
    $scope.formula = [result];
};

    });

1 个答案:

答案 0 :(得分:1)

您收到该错误是因为您没有在ng-model中分配变量。 因此,请更改ng-model="formula.join('')"以使用变量:例如:ng-model="total"

并在您的控制器中,对于每次计算,只需将此变量指定给formula.join(&#39;&#39;)

$scope.add = function(item) {
    if ($scope.formula == '0') $scope.formula = [item];
    else $scope.formula.push(item);
    $scope.total = $scope.formula.join('');
  };
  $scope.remove = function() {
    $scope.formula.pop();
    if ($scope.formula.length == 0) $scope.formula = ['0'];
    $scope.total = $scope.formula.join('');
  };
  $scope.eval = function() {
    var result = eval($scope.formula.join(''));
    $scope.formula = [result];
    $scope.total = $scope.formula.join('');
  };