AngularJS变量基于其他int变量

时间:2015-09-29 00:08:20

标签: javascript angularjs html5 scope data-modeling

非常新的开发者。
试图制作一个费用计算器,其中表中输入的整数之和(每个都有一个特定的默认值)成为另一个变量的int值。我觉得我错过了一些简单的东西,但我不能为我的生活弄清楚什么。

javascript / angular下面

var app = angular.module('expenses', []);
app.controller('mainCtrlr', function($scope) {
    var expenseTotal<----variable I cannot get to work

    var expenseOne;
    var expenseTwo;
    var expenseThree;

    $scope.expenseOne = 270;
    $scope.expenseTwo = 265;
    $scope.expenseThree= 65;
});

填充此表的数据

<div ng-app="expenses" ng-controller="mainCtrlr">
<table>
    <tr>
    <td> Expense </td><td><input type= int ng-model="expenseOne"></td>
    </tr>
    <tr>
    <td>Other Expense </td><td><input type=int ng-model= "expenseTwo"></td>
    </tr>
    <tr>
    <td>Third Expense </td><td><input type=int ng-model= "expenseThree"></td>
    </tr>
    </table>
Total {{expenseTotal}}
</div>

我无法让{{expenseTotal}}显示NaN以外的任何内容。我希望它是一个可用的变量,可以考虑到其他方程,但要基于费用的总和。有谁知道我的javascript文件中还有什么需要才能使这个工作?

提前感谢,如果以前曾被问过我很抱歉,但我无法在任何地方找到它。

2 个答案:

答案 0 :(得分:0)

{{expenseTotal}}引用$scope.expenseTotal,因此您可以在控制器中设置它:

app.controller('mainCtrl', function($scope) {
    $scope.expenseTotal = 4; // Do your calculations here
});

或者您可以在模板中引用控制器:

<div ng-controller="mainCtrl as ctrl">
    Total {{ctrl.expenseTotal}}
</div>

如果你想要添加三个变量,你可以写:

<div ng-controller="mainCtrl">
    ...
    Total {{expenseOne + expenseTwo + expenseThree}}
</div>

在这种情况下,不需要总变量。

答案 1 :(得分:0)

angular.module('expenses', [])
    .controller('mainCtrlr', function($scope) {
        $scope.expenseOne = 270;
        $scope.expenseTwo = 265;
        $scope.expenseThree = 65;
        $scope.expenseTotal = $scope.expenseOne + $scope.expenseTwo + $scope.expenseThree;
    });

var声明不会自动添加到作用域中,因此如果您希望它们在视图中可用,使用括号,则需要在控制器中将它们定义为$ scope变量的属性。