【问题标题】:Make ng-model that's not automatically updating the value制作不会自动更新值的 ng-model
【发布时间】:2015-09-02 08:55:19
【问题描述】:

我有一个<input>,显示一个数字。我使用ng-model 将此数字绑定到一个变量。我的问题是我不希望变量仅在输入时更改,我希望它在按钮单击时更改,但我还希望输入中显示的默认值是存储在变量中的值。

为了稍微清楚一点:

<input type="number" ng-model="foo">
<button ng-click="updateFoo()">Update foo</button>
{{foo}}

我希望foo 仅在按下按钮时反映更改,但如果我刷新页面,{{foo}} 将显示一些值(存在检索值的逻辑)。

我目前的做法,在我的 AngularJS 控制器中:

$scope.foo = 5;

$scope.updateFoo = function(num){
  $scope.foo = num;
}

和 HTML:

<input type="number" ng-model="not_in_controller">
<button ng-click="updateFoo(not_in_controller)">Update foo</button>
{{foo}}

这可以按我的意愿工作,但默认情况下输入为空。

另一个想法是使用两个变量,一个用于演示,另一个用于单击按钮后设置

【问题讨论】:

  • 您已经在使用 2 个变量;要初始化,只需在控制器中添加$scope.not_in_controller = $scope.foo;(并为not_in_controller 选择一个更好的名称)。

标签: html angularjs angular-ngmodel


【解决方案1】:

只需使用ng-init 指令:

<input type="number" ng-model="not_in_controller" ng-init="not_in_controller=5">
<button ng-click="updateFoo(not_in_controller)">Update foo</button>
{{not_in_controller}}

【讨论】:

    【解决方案2】:

    只需在您的&lt;input /&gt; 中使用value="{{ foo }}"

    这里有一个 jsfiddle:http://jsfiddle.net/5s3cjyuw/

    【讨论】:

      猜你喜欢
      • 2012-09-19
      • 2016-12-09
      • 1970-01-01
      • 2017-01-05
      • 2017-12-12
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      相关资源
      最近更新 更多