视图变量不会在$ scope中注入

时间:2016-10-17 08:56:08

标签: angularjs

观点:

<div class="numbers">
    {{calc.amount || 0 }}
</div>
<div class="keypad">
    <div class="number-slot"><button ng-click="numberPressed(1)" class="number">1</button></div>
</div>

控制器:

app.controller('pay-amount', function ($scope, $state, $cordovaBarcodeScanner, ionicMaterialInk) {

    $scope.numberPressed = function (number) {
        console.log(number + " pressed!");
        $scope.calc = {
            amount: "" + $scope.calc.amount + number
        }
    };

    ionicMaterialInk.displayEffect();
});

在调用numberPressed(1)之前没有错误:

  

“ionic.bundle.js:26794 TypeError:无法读取属性'amount'   未定义”。

在检查$ scope时,我找不到我在视图中定义的“calc”对象。我在这里缺少什么?

4 个答案:

答案 0 :(得分:0)

您需要在使用之前声明$ scope变量,

$scope.calc = {amount:0};

<强> DEMO

答案 1 :(得分:0)

试试这个,

$scope.numberPressed = function (number) {
    console.log(number + " pressed!");
    $scope.calc = {amount:''};
    $scope.calc = {
        amount: "" + $scope.calc.amount + number
    }
    console.log($scope.calc);
};

答案 2 :(得分:0)

calc上从未设置$scope,因此它会尝试在amount上找到undefined

您可以进行2次简单的更改

$scope.calc = {};
$scope.numberPressed = function (number) {
    console.log(number + " pressed!");
    $scope.calc.amount = ($scope.calc.amount || 0) + number
}

$scope.calc = { amount: 0 };
$scope.numberPressed = function (number) {
    console.log(number + " pressed!");
    $scope.calc.amount = $scope.calc.amount + number
}

答案 3 :(得分:0)

试试这个,

$scope.calc = { amount: 0 };
$scope.numberPressed = function (number) {
     console.log(number + " pressed!");
     $scope.calc.amount = $scope.calc.amount + number
}