簡體   English   中英

AngularJS子指令取決於父指令的可重用性

[英]AngularJS child directive depending on parent directive reusability

讓我們定義一個簡單的場景,其中博客具有Post列表,每個列表包含Comment和其他Object

在構建“ Post頁面時,我可以對定義以下元素進行圖像處理:

<post post="post"></post>
<comments post="post"></comments>
<objects post="post"></objects>

要么:

<post post="post">
    <comments></comments>
    <objects></objects>
</post>

為了提供可重用性,與元素關聯的每個指令都有其自己的隔離范圍。

然后考慮例如與<comments>關聯的指令,我可以為其提供一個Add按鈕,一個Reload comments按鈕等。這很容易,只要其功能限於自己的范圍即可。

在第一次加載Post時,在與<comments>關聯的指令的link方法中加載Comment (父級) Post更改時,如何觸發Comment重新加載?

  1. 在與<comments>關聯的指令中,我應該放置一個scope.$watch('post')來偵聽關聯的Post更改時的情況,並在更改時觸發Comment的重載嗎?
  2. 我應該在Post指令中創建一個register函數,其中CommentObject訂閱它們自己的控制器,並在需要重載時從Post函數得到通知嗎? 也就是說,手動實現的觀察者模式。
  3. $broadcast$on 不確定如何使用隔離范圍實現它們。

我要說的最合適的事情是使用事件。 如果范圍是隔離的,則可以從指令控制器(或另一個控制器)廣播,如下所示:

AngularJS:來自指令的廣播事件

這是一些代碼,演示如何處理隔離范圍和事件等:

http://plnkr.co/edit/tpl:rfqcl9AHEoJZEEJxyNn2?p=preview

app.directive('post', function() {
  return {
    scope: {},
    link: function(scope, elem, attrs) {
      console.log('post');
    },
    controller: function($scope) {
      tellComments = function() {
        console.log('telling comments');
        $scope.$broadcast('heyComments');
      };
    },
    template: '<button ng-click="tellComments()">sup</button><div comments></div>'
  };
})

app.directive('comments', function() {
  return {
    scope: {},
    link: function(scope, elem, attrs) {
      console.log('comments');
    },
    controller: function($scope) {
      $scope.$on('heyComments', function() {
        console.log('sup post!');
      });
    }
  }
})

和模板:

  <body ng-controller="MainCtrl">
    <div post>
      <button ng-click="tellComments()">click me</button>
    </div>
  </body>

因此,單擊按鈕或執行調用“ tellComments”功能的其他任何操作(例如,加載某些數據),然后將其發送到子指令中,該指令由控制器作用域處理-與指令作用域不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM