繁体   English   中英

Angular:带有父子指令的模板

[英]Angular: template with a parent and child directive

我有这个简单的例子...

码:

angular
      .module('app', [])
      .directive('parentDirective', parentDirective)
      .directive('childDirective', childDirective);

    function parentDirective() {
      return {
        restrict: 'E',
        scope: true,
        //template: 'My job is {{job}}', 
        controller: function($scope) {
          $scope.job = 'trashman';
          $scope.say = function(job) {
            $scope.job = job;
            alert($scope.job);
          }
        }
      };
    }

    function childDirective() {
      return {
        restrict: 'E',
        link: function(scope) {
          scope.say('shoe shine boy');
        }
      };
    }

标记:

    <parent-directive>
        <child-directive></child-directive>
    </parent-directive>

这按预期工作。 我遇到的问题是理解为什么我不能将模板添加到parentDirective并获得相同的结果。 如果取消注释template属性,则绑定不会更改,并且不再触发警报。 有人可以简单地向我解释一下这里发生了什么吗? 也许可以帮助充实我的榜样? 我通过例子学习:)

您可以在父级上设置模板属性,并在模板内部使用子级伪指令。 理想情况下,它应该自动呈现。

就像是:

angular .module('app',[]).directive('parentDirective',parentDirective).directive('childDirective',childDirective);

function parentDirective() {
  return {
    restrict: 'E',
    scope: true,
    template: '<div>{{job}} is seen<child-directive></child-directive></div>'
    //template: 'My job is {{job}}', 
    controller: function($scope) {
      $scope.job = 'trashman';
      $scope.say = function(job) {
        $scope.job = job;
        alert($scope.job);
      }
    }
  };
}

function childDirective() {
  return {
    restrict: 'E',
    template: '<div>I will be renderred</div>',
    link: function(scope) {
      scope.say('shoe shine boy');
    }
  };
}

现在,您可以在任何地方使用父指令,它还将在其内部呈现子指令。

就像是:

<parent-directive></parent-directive>

Angular现在会看到它,找到父指令,将其渲染,在其内部使用的是子指令,渲染子HTML。

当您使用指令模板时,它会用模板替换指令内部内容,这很可能是因为从不呈现内部指令。

您需要在父模板中使用ng-transclude才能在父指令模板内发出子指令html。 在指令定义对象标记上

transclude: true,

template: '<div> My job is {{job}} <ng-transclude></ng-transclude></div>'

这来自$compile文档

替换指令元素的内容(默认)。

替换指令的元素本身(如果replace为true,则不建议使用)。

包装指令元素的内容(如果transclude为true)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM