通过解析器传递值时,角度$scope不更新

Angular $scope not updating when passing value through parser

本文关键字:角度 scope 更新      更新时间:2023-09-26

请注意,即使通过验证的值也不会通过解析器使其完整。解析器返回正确的值,但是当格式化程序被调用时,旧值仍然存在于模型中。有人可以向我解释一下吗?

这是 plnkr

http://plnkr.co/edit/uSLkKtLZIU63wRou3x8V?p=preview

和代码

angular.module('timeEntryModule', []).directive('timeEntryTotalHoursInput', function() {
return {
    require: '^ngModel',
    link: function($scope, $element, $attrs, ngModel) {
        ngModel.$formatters.push(function (modelValue) {
            if (modelValue === 0) {
                return undefined;
            } else {
                return modelValue.toFixed(2);
            }
        });
        ngModel.$parsers.push(function (viewValue) {
            var tempVal = parseFloat(viewValue);
            if (tempVal) {
                ngModel.$setValidity('timeEntryInputError', true);
                ngModel.$modelValue = tempVal;
            } else {
                ngModel.$setValidity('timeEntryInputError', false);
                ngModel.$modelValue = undefined;               
            }
            return ngModel.$modelValue;            
        });
    }
};

});

angular.module('timeEntryModule').controller('TimeEntryCtrl', ['$scope', function ($scope) {
    $scope.testproperty = 2;
}]);
<!doctype html>
<html ng-app="timeEntryModule">
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
    <script src="script.js"></script>
  </head>
  <body ng-controller="TimeEntryCtrl">
    <input ng-model="testproperty" time-entry-total-hours-input />
  </body>
</html>

提前感谢!

所以我玩了你的 plnkr,我认为你会更好地响应模糊事件,这是我很快想到的普罗提

我认为在这种情况下,您可以更好地控制事情。