簡體   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