【问题标题】:Input element not being updated after model attribute changed模型属性更改后输入元素未更新
【发布时间】:2014-11-26 22:26:54
【问题描述】:

我使用按钮将值附加到输入元素。尽管模型变量已更新,但输入值保持不变。如何解决?

<input type="text"
                           class="form-control"
                           id="inputSecurityCode"
                           style="width: 100%"
                           placeholder="4 digits"
                           name="inputSecurityCode"
                           ng-model="reservation.securityCode"
                           ng-pattern="patterns.securityCode"
                           ng-focus="focused('inputSecurityCode')"
                           ng-blur="blurred('inputSecurityCode')"
                            />
<button type="button" ng-click="numButtonClick(1)">1</button>

AngularJS

    $scope.reservation = {
            securityCode: undefined
        };

    $scope.numButtonClick = function(num){
                switch($scope.focusedInput){
                    case 'inputSecurityCode':
                        $scope.reservation.securityCode += num;
                        break;
                }

        };
$scope.patterns = { 
                        securityCode : /^[0-9]{4}$/
    };

更新

可能是因为起始值是 undefined、NaN 并且当尝试 NaN 加整数时返回 NaN 并且无法添加到输入中。应该是null 而不是undefined?

更新 2

所有undefined 都已更改为nulls,但观察到的行为相同。

更新 3

我发现当我删除 ng-pattern="patterns.securityCode" 时一切正常。怎么会?

【问题讨论】:

  • 您说“模型变量已更新”。所以我猜不是?

标签: javascript angularjs


【解决方案1】:

编辑:这似乎不是 OP 的问题,可能是不正确的信息。

这是因为 AngularJS 不会自动传播对象原始属性的更改。

像这样手动重新应用绑定:

$scope.numButtonClick = function(num){
            switch($scope.focusedInput){
                case 'inputSecurityCode':
                    $scope.$apply(function(){
                         $scope.reservation.securityCode += num;
                    });
                    break;
            }

    };

【讨论】:

  • 我收到Error: [$rootScope:inprog]
  • 我进行了编辑。试试看。如果它不起作用,则问题可能是其他问题。
  • 在使用 $scope.reservationSecurityCode 而不是使用原始属性 securityCode 的对象保留时,您的代码是否有效?
  • 改成$scope.reservationSecurityCode 后出现同样的错误
  • 在将一些值放入input 之后,模型变量没有被更新。按下按钮后,现有值被重置,reservationSecurityCode 变为undefined
猜你喜欢
  • 2020-07-18
  • 2011-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-06
  • 2021-08-23
  • 2017-02-26
  • 2016-12-04
相关资源
最近更新 更多