【问题标题】:How to use $scope.$watch and ng-repeat?如何使用 $scope.$watch 和 ng-repeat?
【发布时间】:2016-05-15 04:40:19
【问题描述】:

我有工作代码:

$scope.$watch('vm.reg', function (newValue) {
  if (newValue !=  null) {
    vm.reg = newValue.replace(/\D+/, '');
  }
});
<input type="text" class="form-control" name="dest_regex" ng-model="vm.reg"/>

但我需要将$watch 用于ng-repeat,如下所示:

<div ng-repeat="fi in filterElments">
    <input type="text" class="form-control" name="dest_regex" ng-model="fi.reg"/>

    <!--<input type="text" class="form-control" name="dest_regex" ng-model="fi.reg"/>
    <input type="text" class="form-control" name="dest_regex" ng-model="fi.reg"/>
     .................. -->
</div>

【问题讨论】:

  • 什么不起作用..请详细解释一下。
  • 为什么要使用 replace(/\D+/, '');, 进行替换?
  • 你不需要 $watch,使用 ng-change,这个属性就像你输入的 $watch 一样工作
  • @AmitRamoliya,我需要分别检查每个输入。问题是 ng-repeat 中的一个模型 fi.reg,因为我无法单独检查每个输入

标签: javascript angularjs


【解决方案1】:

对于您的具体情况,我建议查看 ngModelController $parsers 和 $formatters。

https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

https://stackoverflow.com/a/22843592/274500

【讨论】:

    【解决方案2】:

    ng-在 ng-repeat 中为您的 ng-models 更改为 $watch

    你可以检测输入值是否有变化

    $scope.replacing = function(item){
      //do somthing
    }
    <div ng-repeat="fi in filterElments">
        <input type="text" class="form-control" name="dest_regex" ng-model="fi.reg" ng-change="replacing(fi)"/>
    </div>

    【讨论】:

    • 谢谢你,ng-change 真的很有帮助
    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 2017-02-28
    • 2016-04-27
    • 1970-01-01
    相关资源
    最近更新 更多