从ng-messages中提取ng-message密钥

时间:2015-03-26 16:56:33

标签: javascript angularjs compilation transclusion

我需要创建一个指令 myDirective ,它读取其中的所有ng-message键,它仍然会创建一个有效的ng-messages元素:

指令模板:

<div id="myDirective">
  <div ng-messages="myform.$error" ng-transclude></div>
</div>

用法:

<my-directive>
  <div ng-message="required">something is required</div>
  <div ng-message="custom">custom validation</div>
</my-directive>

所以在这种情况下,我想得到一个&#34; required&#34;和#34; custom&#34;。问题是我不能这样做,因为当我的指令进入它自己的链接函数时,所有ng-messsage元素已经被隐藏(从DOM中移除以更准确)。如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

在编译阶段删除了该指令的内容,因为你的指令有transclude: true(我假设是这样,因为你使用的是ng-transclude)。

在这种情况下,内容可通过传入的transclude函数获得(这实际上是ng-transclude在封面下使用的内容)。

transclude函数是link(或预链接)函数的第5个参数:

link: function(scope, element, attrs, ctrls, transclude){
  var transcludedContents; // jqLite of the contents

  transclude(function(clone){
    transcludedContents = clone;
  });

  // do whatever you do to extract ng-message values from transcludedContents
  // just remember, that it could also come in the form:
  // <ng-message when="required"> and 
  // <div ng-message-exp="errorMessage.type">
}

我们中间的懒人可能不想处理DOM计数,因此你可以为ng-message指令创建另一个处理程序,它与你的my-directive进行交互以注册自己:

.directive("myDirective", function() {
  return {
    transclude: true,
    templateUrl: "myDirective.template.html",
    controller: function() {
      var messages = [];
      this.registerNgMessage = function(val) {
        messages.push(val);
      };
    }
  };
})
.directive("ngMessage", complementaryNgMessageDirective)
.directive("ngMessageExp", complementaryNgMessageDirective);

function complementaryNgMessageDirective() {
  return {
    priority: 10, // must be higher than ngMessage, because ngMessage is terminal
    require: "^?myDirective", // must be optional not to break existing code
    link: function(scope, element, attrs, myDirectiveCtrl) {

      if (!myDirectiveCtrl) return; // do nothing, if not paired with myDirective

      var staticExp = attrs.ngMessage || attrs.when;
      var dynamicExp = attrs.ngMessageExp || attrs.whenExp;

      var val;
      if (dynamicExp) {
        val = scope.$eval(dynamicExp);
      } else {
        val = staticExp;
      }

      myDirectiveCtrl.registerNgMessage(val);
    }
  };
}