【问题标题】:AngularJS: Two-Way Data Binding with Number InputsAngularJS:带有数字输入的双向数据绑定
【发布时间】:2014-07-09 05:57:16
【问题描述】:

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

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

任何帮助将不胜感激。

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

使用$watch:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    });

    上面只会在调用控制器时设置轮胎值,而不是在自行车值发生变化时设置轮胎值。这可以通过在 Bikes 上添加一个手表来实现,它会在 Bikes 值发生变化时轮胎值变化

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

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

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

    })

    });

    【讨论】:

      【解决方案3】:

      两种方式:

      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;
        });
      });
      

      【讨论】:

        【解决方案4】:

        试试这个:

        在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;
        };
        

        希望对你有帮助.........

        【讨论】:

          【解决方案5】:

          有几点:

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

          更新

          首先,$watchGroup only came in at v1.3.0-beta.6 - 在your script 中,您使用的是 v1.2.10。

          其次,这里引用的所有 jsbin 都表明,当更新 bikes 属性时,轮胎属性正在更新。 Here's another jsbin 更清楚地显示了这一点。

          所以我还是不确定你在这里追逐什么?

          【讨论】:

          • 不确定你的意思 - 代码只是展示了使用“watch”来保持你的值更新的原则。如果您在更新“轮胎”后需要更新“自行车”,您只需添加第二块手表即可。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-08-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多