[英]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
重新加載?
<comments>
關聯的指令中,我應該放置一個scope.$watch('post')
來偵聽關聯的Post
更改時的情況,並在更改時觸發Comment
的重載嗎? Post
指令中創建一個register
函數,其中Comment
和Object
訂閱它們自己的控制器,並在需要重載時從Post
函數得到通知嗎? 也就是說,手動實現的觀察者模式。 $broadcast
和$on
? 不確定如何使用隔離范圍實現它們。 我要說的最合適的事情是使用事件。 如果范圍是隔離的,則可以從指令控制器(或另一個控制器)廣播,如下所示:
這是一些代碼,演示如何處理隔離范圍和事件等:
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.