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

AngularJS: Two-Way Data Binding with Number Inputs

本文关键字:数据绑定 数字输入 AngularJS      更新时间:2023-09-26

我试图使用角数据绑定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;
    });
});

你想要实现的不是双向绑定。

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

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

});

上面的代码只会在调用控制器时设置tires的值,而不会在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;
};

希望能有所帮助.........

以下几点:

  • 你应该在一个"model"类型的属性中定义你的模型——详细信息见这里:http://zcourts.com/2013/05/31/angularjs-if-you-dont-have-a-dot-youre-doing-it-wrong/

  • 为了更新"tires"属性,你需要"观察"bikes"属性的变化。

这是一个更新的JSBin,展示了如何做到这一点:http://jsbin.com/kiqivule/15/edit?html,js,output

更新

首先,$watchGroup只在v1.3.0-beta版本出现。在你的脚本中,你使用的是v1.2.10.

其次,这里引用的所有jsbin都显示,当脚踏车属性更新时,tires属性也在更新。下面是另一个jsbin,它更清楚地显示了这一点。

所以我还是不知道你在追求什么?