繁体   English   中英

AngularJS:带数字输入的双向数据绑定

[英]AngularJS: Two-Way Data Binding with Number Inputs

我正在尝试将angular用于数据绑定input type="number"元素,但似乎无法弄清楚如何使绑定正常工作。 例如,当我更新任何值时,我希望绑定到它的值也将更新。

JSBin: http : //jsbin.com/kiqivule/3/edit

任何帮助,将不胜感激。

使用$watch

app.controller('MyCtrl', function($scope) {
    $scope.tires = $scope.bikes * 2;

    $scope.$watch('bikes', function(){
        $scope.tires = $scope.bikes * 2;
    });
});

有两件事:

这是更新的JSBin,其中显示了如何执行此操作: http ://jsbin.com/kiqivule/15/edit?html,js,output

更新资料

首先, $ watchGroup仅出现在v1.3.0-beta.6中 -在脚本中您使用的是v1.2.10。

其次,这里引用的所有jsbins都表明,在更新bikes属性时,轮胎属性也正在更新。 这是另一个jsbin ,它更加清楚地显示了这一点。

所以我仍然不确定你在这里追逐什么?

您要实现的不是2向绑定。

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

$scope.tires = $scope.bikes * 2;

});

以上仅在调用控制器时设置轮胎值,而在自行车的值更改时不设置轮胎值。 这可以通过在Bikes上添加手表来实现,当手表的价格发生变化时,该手表会累加值

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

$scope.$watch('bikes', function(){

` $scope.tires = $scope.bikes * 2;`

})

});

两种方式:

1-`ng-change:

<input type="number" 
    ng-change="tires = bikes * 2"
    min="0" ng-model="bikes" placeholder="Bikes" id = "bikes"/>

要么....

2- $watch

app.controller('MyCtrl', function($scope) {
  $scope.$watch('bikes', function(newValue, oldValue) {
      if(newValue === oldValue) {
          return; // Angular calls watch at initialization with no change
      }
      $scope.tires = $scope.bikes * 2;
  });
});

尝试这个:

在html中,

使用ng-change:

<input type="number" min="0" ng-model="bikes" placeholder="Bikes"
  ng-change="Calc()" id = "bikes"/>

在JS中

$scope.Calc = function(){
   $scope.tires = $scope.bikes * 2;
};

希望能帮助到你.........

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM