将模型传递给angularjs中的控制器功能

时间:2016-06-27 21:19:16

标签: angularjs

我的代码在哪里出错了?当您单击按钮时,必须显示第一个数字和第二个输入数字。



app.controller('AddSum', ['$scope', function ($scope) {
    $scope.sum = 0;
    $scope.add = function (fnumber, snumber) {
        $scope.a = $scope.fnumber;
        $scope.b = $scope.snumber;
        $scope.sum = $scope.a + $scope.b;
      
    }; 
}]);




HTML



 <table ng-controller="AddSum">
            <tr>
                <td>Enter First Number:</td>
                <td><input ng-model="fnumber"></td>
            </tr>
            <tr>
                <td>Enter Second Number:</td>
                <td><input ng-modle="snumber"  /></td>
            </tr>
            <tr>
                <td><button ng-click="add()">SUM</button></td>
                <td><p>Sum:{{sum}}</p></td>
            </tr>
           
  </table>
&#13;
&#13;
&#13;

它不起作用,请参阅修改后的代码。

&#13;
&#13;
                
                app.controller('AddSum', ['$scope', function ($scope) {
    $scope.sum = 0;
    $scope.add = function (fnumber,snumber) {
        $scope.a = $scope.fnumber;
        $scope.b = $scope.snumber;
        $scope.sum = parseInt($scope.a) + parseInt($scope.b);
      
    }; 
}]);
&#13;
 <table ng-controller="AddSum">
            <tr>
                <td>Enter First Number:</td>
                <td><input ng-model="fnumber"></td>
            </tr>
            <tr>
                <td>Enter Second Number:</td>
                <td><input ng-model="snumber" /></td>
            </tr>
            <tr>
                <td><button ng-click="add(fnumber,snumber)">SUM</button></td>
                <td><p>Sum:{{sum}}</p></td>
            </tr>
    </table>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

你有一个错字。

更改

 <td><input ng-modle="snumber"  /></td> 

<td><input ng-model="snumber"  /></td>

然后您需要将输入解析为数字

变化       $scope.sum = $scope.a + $scope.b; 至       $scope.sum = parseInt($scope.a) + parseInt($scope.b); 虽然你想要做一些更优雅的事情,但是会做到这一点。

答案 1 :(得分:0)

最后我得到了解决方案。

app.controller('AddSum1',function($ scope){

$scope.add = function (num1, num2) {
    $scope.sum = parseInt(num1) + parseInt(num2);
}; 

});