无法从指令

时间:2018-05-04 17:13:40

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

在下面的示例中,当用户关闭弹出窗口时出错,我试图将控制器值设置为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>

1 个答案:

答案 0 :(得分:1)

要操纵$viewValue,请使用$setViewValue功能,它会照顾更新$modelValue并调用中间$$parsers$$formatters$$validators管道在幕后。

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