Angular Directive formatter / render不会更新

时间:2015-02-17 15:18:46

标签: javascript angularjs angularjs-directive

我写了一个非常简单的directive,它会变成分钟 进入范围滑块,并在其旁边显示小时分钟。 问题是移动范围滑块会更新范围, 因此,Watch和Parser会被调用,但Formatters / Render不再被调用。

所以我的会议记录会更新并传播到更改模型,但是指令"内部" 小时分钟永不更新。

仅当我在ng-model值上从外部进行更改时。

我不确定会发生什么,因为类似的指令都按预期工作。 :■

// Here is a shortened version
angular.module('TestApp', ['TestDirectives']);

angular
.module('TestDirectives', [])
.directive("rangeMinutes", [function RangeMinutesDirective () {
    return {
        require: 'ngModel',
        replace: true,
        scope: true,
        templateUrl: 'minutesHoursRange.html',
        link: function (scope, element, attributes, ngModelCtrl) {

            ngModelCtrl.$formatters.push(function (modelValue) {
                var totalMinutes = (modelValue ? modelValue : 0);
                return {
                    totalMinutes : totalMinutes,
                    hours : Math.floor(totalMinutes/60),
                    minutes : parseInt(totalMinutes%60, 10)
                };
            });

            ngModelCtrl.$render = function () {
                if (!ngModelCtrl.$viewValue) {
                    ngModelCtrl.$viewValue = {
                        hours: 0, minutes: 0, totalMinutes: 0
                    };
                }
                scope.totalMinutes = ngModelCtrl.$viewValue.totalMinutes;
                scope.hours = Math.floor(scope.totalMinutes/60);
                scope.minutes = parseInt(scope.totalMinutes%60, 10);
            };

            scope.$watch('totalMinutes', function () {
                ngModelCtrl.$setViewValue({
                  totalMinutes: scope.totalMinutes,
                  hours: scope.hours,
                  minutes: scope.minutes
                });
            });

            ngModelCtrl.$parsers.push(function (viewValue) {
                return parseInt(viewValue.totalMinutes, 10);
            });
        }
    };
}])
.controller("TestController", ["$scope", function ($scope) {
  $scope.testObject = { testValue: 40 };
}]);

指令的模板:

<div class="form-inline minutesHoursRange">
    <div class="form-group">
        <label>
            <input type="range" min="0" max="100" step="1" class="form-control"
               data-ng-model="totalMinutes"/> {{hours}} hrs {{minutes}} mns
        </label>
    </div>
</div>

视图:

<body data-ng-app="TestApp" data-ng-controller="TestController">
    <div data-ng-model="testObject.testValue" data-range-minutes></div>
</body>

1 个答案:

答案 0 :(得分:2)

您在$watch媒体资源上没有totalMinutes,只需添加:

scope.$watch('totalMinutes', function domToViewValue () {
        scope.hours = Math.floor(scope.totalMinutes/60),
        scope.minutes = parseInt(scope.totalMinutes%60, 10);
});

一切正常。

Working Plunker