【问题标题】:Cannot set ng-model value to null from directive无法从指令将 ng-model 值设置为 null
【发布时间】:2018-05-04 17:13:39
【问题描述】:

在下面的示例中,当用户关闭弹出窗口时出现错误,我试图将控制器值设置为 null。但是,尽管我正在更新 $viewValue$modelValue,但 angularjs 不知何故采用了旧值。如果您输入input 任何值,例如1,然后按Tab,1 秒后您将看到1.00,但是我试图将其设置为null(并查看值应该是空字符串)。

(function () {

  var module = angular.module('TestApp', []);

  module.directive('decimalTextbox', ['$timeout', function ($timeout) {
    return {
      restrict: 'A',
      replace: false,
      require: '?ngModel',
      scope: {
        onValidate: '='
      },
      link: function (scope, element, attrs, ctrl) {
      
        ctrl.$formatters.unshift(function (value) {
          return value != null ? parseFloat(value).toFixed(2) : '';
        });
        
        ctrl.$parsers.unshift(function (value) {
          return value == '' ? null : parseFloat(value);
        });
        
        $(element).on('blur', function () {
          $timeout(function () {
            var result = { isValid: true, value: ctrl.$modelValue };
            scope.onValidate(result);
            if (!result.isValid) {
              // show popup with close button here
              // to simplify example I use setTimeout
              setTimeout(function () {
                $(element).val('');
                ctrl.$viewValue = '';
                ctrl.$modelValue = null;
                scope.$apply();
                console.log(ctrl.$modelValue);
              }, 1000);
            }
          });
        });
      }
    };
  }]);
  
  module.controller('TestController', ['$scope', function (scope) {
    
    scope.someValue = 3;
    
    scope.validate = function (result) {
      result.isValid = false;
    };
    
  }]);

})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>

<div ng-app="TestApp" ng-controller="TestController">
  <input
    type="text"
    ng-model="someValue"
    decimal-textbox=""
    on-validate="validate">
  <h3>{{ someValue }}</h3>
</div>

【问题讨论】:

标签: angularjs angularjs-directive angularjs-ng-model


【解决方案1】:

要操作$viewValue,请使用$setViewValue函数,它会小心更新$modelValue并在后台调用中间$$parsers$$formatters$$validators管道。

//ctrl.$viewValue = ''; //instead of this
ctrl.$setViewValue(''); //use this.
//ctrl.$modelValue = null; //no need to set $modelValue

【讨论】:

    猜你喜欢
    • 2020-08-28
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 2014-10-05
    相关资源
    最近更新 更多