用一个属性预填充输入,但将ng-model设置为不同的属性

Angular.js - prefill input with one property, but set ng-model to different property

本文关键字:属性 ng-model 但将 设置 填充 一个 输入      更新时间:2023-09-26

我有我的输入:

input(ng-model='amount' ng-init='amount = (amount == 0) ? total : amount')

所以我需要将用户输入的值保存为amount,然而,当页面加载时,如果amount恰好为零,那么用total预填充它。

一切都很好,但是,我有一个间隔运行来刷新来自服务器的数据,所以当刷新发生时,我猜测模型值amount发生变化,并且它将输入设置为"0"(如果amount为零)。我该如何解决这个问题?

您的问题是使用ng-init,首先,它是不适合使用它的任何其他除了混叠ng-repeat特殊属性,如$index, $first等…在每个摘要周期中都不会监视Ng-init 'Ed表达式的更改。此外,视图值更新是在ng-model更新时完成的。所以你不会看到它在之后的消化循环中被评估。不要使用ng-init,只需将控制器中的ng-model本身设置为默认值即可。

 $scope.amount = $scope.amount || $scope.total;

或者你也可以使用ng-model的getter setter选项

创建新的变量inputAmount,绑定到你的输入。

input(ng-model='inputAmount' ng-init='inputAmount = (amount == 0) ? total : amount')

你可以在控制器的模型上使用可选赋值。

$scope.myModel = $scope.myModel || $scope.prefilled

我创建了codeopen的例子:http://codepen.io/skymk/pen/vOyPWB?editors=101