【问题标题】:Angular Directive access internal ng-model controllerAngular 指令访问内部 ng-model 控制器
【发布时间】:2017-12-13 09:26:37
【问题描述】:

我有一个 angular-moment-picker 的自定义包装器指令。我使用 cutrom 模型属性 (dp-model) 和内部 ng-model (dpModelObject)。我想访问这个内部模型控制器来设置它的原始和有效性属性。

有可能吗?

(function() {

	  angular.module('app').directive('datePicker', datePicker);

    datePicker.$inject = [];

    function datePicker() {
      return {
        restrict: 'E',
              scope: {
                  dpModel: '=',
                  dpRequired: '='
              },
              // replace: true,
              templateUrl: template.html,

              link: function($scope, $element, $attrs, ngModelCtrl)
              {
                  if ($scope.dpModel) {
                      $scope.dpModelFormatted = moment($scope.dpModel, 'YYYY-MM-DD').format('YYYY. MM. DD.');
                  }

                  $scope.$watch('dpModelObject', function(date) {
                      if (date) {
                          $scope.dpModel = moment(date).format('YYYY-MM-DD');
                      }
                  }, true);
              }
      };
	}

})();
<div class="input-group datepicker">
    <input type="text" class="form-control"
        moment-picker="dpModelFormatted"
        ng-model="dpModelObject"
        ng-required="dpRequired"
    >
    <span class="input-group-addon">
        <i class="glyphicon glyphicon-calendar"></i>
    </span>
</div>

【问题讨论】:

    标签: javascript angularjs angularjs-directive angular-ngmodel


    【解决方案1】:

    您需要在指令定义对象中设置require 属性。

    来自文档:

    需要另一个指令并将其控制器作为第四个参数注入链接函数。

    return {
        restrict: 'E',
        require: 'ngModel', // here
        scope: {
           ngModel: '=', // and call it by the attribute name
           dpRequired: '='
        },
        ....
    

    那么你的链接函数中的第四个参数将引用ngModelControllerthe official docs 更详细地介绍这一点

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-07
      相关资源
      最近更新 更多