从范围 angular 动态访问元素

Accessing element dynamically from scope angular

在像下面这样的指令中,我们如何在通过指令中的属性传递的其他元素上手动设置验证。下面的代码给出错误 otherField does not exist while it should take value of this variable and not directly name of this field in scope string.

app.directive('higherThan', [
  function() {

    var link = function($scope, $element, $attrs, ctrl) {

      var otherField = $attrs.otherField;
      $scope.otherField.$setValidity('lowerThan', true);
      //Other details of directive not kept for simplicity
    }

    return {
      require: 'ngModel',
      link: link
    };

  }
]);

HTML

<form name="main_form">
<label>From</label>

<input name="from_date" type="text" class="form-control" ng-model="date_range[0]" lower-than="date_range[1]" ng-required="true" close-text="Close"  />

<label>To</label>

<input name="to_date" type="text" class="form-control" ng-model="date_range[1]" higher-than="date_range[0]" ng-required="true" close-text="Close" other-field="from_date"/>

<span ng-show="main_form.to_date.$error.higherThan">From date should be lower than to date</span>
</form>

$setValidity 应在 NgModelController 对象上调用:

var link = function($scope, $element, $attrs, ctrl) {

    var otherField = $attrs.otherField;
    ctrl.$setValidity('lowerThan', true);
    //Other details of directive not kept for simplicity
}
var otherField = $attrs.otherField;
$scope.otherField.$setValidity('lowerThan', true);

这里有几个问题:

1) var otherField是一个字符串,不是实际输入的

2) 设置 var otherField 后,您实际上并没有将其用于任何用途。

3) 没有 属性 $scope.otherField,这就是您收到错误的原因。

即使你做了 $scope[otherField] 这也会出错,因为 from_date 的 ngModelController 不属于 $scope 它属于 main_form.

您应该尝试使用 console.log($scope) 进行调查。

应该是:

app.directive('higherThan', [
    function($parse) {

        var link = function($scope, $element, $attrs, ctrl) {

            var otherField = $parse($attrs.otherField)($scope);
            otherField.$setValidity('lowerThan', true);
            //Other details of directive not kept for simplicity
        }

        return {
            require: 'ngModel',
            link: link
        };

    }
]);


<form name="main_form">
  <label>From</label>
  <input name="from_date" type="text" class="form-control" ng-model="date_range[0]" lower-than="date_range[1]" ng-required="true" close-text="Close" />
  <label>To</label>
  <input name="to_date" type="text" class="form-control" ng-model="date_range[1]" higher-than="date_range[0]" ng-required="true" close-text="Close" other-field="main_form.from_date" />
  <span ng-show="main_form.to_date.$error.higherThan">From date should be lower than to date</span>
</form>