指令中的程序变量更改不会运行父作用域验证

时间:2016-09-29 09:29:55

标签: javascript angularjs validation angularjs-scope

我有一个在地图中包含圆圈的表单。 “圈选择器”实现为一个指令,用于呈现GoogleMaps映射并从父作用域(表单所在的位置)更新双向绑定对象(在指令范围内使用'=')。

代码如下:

表单HTML

<!-- View uses controllerAs:"vm" -->
<circle-location-picker circle="vm.circle"></circle-location-picker>
<input type="hidden" ng-model="vm.circle.center" name="center" required>
<input type="hidden" ng-model="vm.circle.radius" name="radius" required>

圈选择器指令(摘录):

angular
  .module('frontend')
  .directive('circleLocationPicker', CircleLocationPicker);

function CircleLocationPicker() {
  return {
     templateUrl: 'app/directives/circleLocationPicker/circleLocationPicker.html',
     restrict: 'E',
     scope: {
       'circle': '='
     },
     controller: MapController
  };

  function MapController($scope, ...) {
    // Called when the circle is changed in the map
    function circleChanged() {
      var center = $scope.gcircle.getCenter();

      $scope.circle.center.latitude = center.lat();
      $scope.circle.center.longitude = center.lng();
      $scope.circle.radius = $scope.gcircle.getRadius();
    }
  }
}

这有效,但现在我正在尝试在圆的半径上添加验证器。

要做到这一点,我已经添加了一个指令(this之后),如下所示:

angular
  .module('frontend')
  .directive('radiusValidator', function () {
    return {
      require: 'ngModel',
      link: function (scope, elm, attrs, ctrl) {
        ctrl.$validators.radius = function (modelValue, viewValue) {
          return !viewValue || viewValue > 250;
        };
      }
    }
  })

验证器在加载时正确运行,但每当我更改映射中的圆圈时(因此在指令中更改了值,在表单控制器中更新它),它就不会再次运行。此外,在包含半径的输入字段中不会更改该值。

最令人惊讶的是,如果我在表单页面中添加“调试按钮”,onClick只会将vm.circle的值记录到控制台,则会在字段中更新该值并运行验证程序

我尝试添加$watch(vm.circle, <function that does the log>),但它不起作用......

我做错了什么或错过了什么?

0 个答案:

没有答案
相关问题