[英]AngularJS directive not reacting to attribute change
我有一個聊天指令,用於在頁面上放置聊天室。
mod.directive('chat', function () {
return {
templateUrl: '/chat',
replace: true,
scope: {
chatID:'@chat',
},
controller: function ($scope, $element, $timeout) {
var id = $scope.chatID
...
},
link: function ...
}
})
HTML 看起來像這樣:
<div class="chat" chat="{{currentChatID}}" ui-view="currentChat"></div>
<div class="content" ui-view="mainContent"></div>
這是在一個名為“標准”的文件中
mod.config(function($stateProvider) {
$stateProvider.state('standard', {
views: {
'main': {
templateUrl: '/tmpl/standard',
controller: function($scope, $timeout) {
$scope.currentChatID = ''
$scope.setCurrentChatID = function(newID) {
$scope.currentChatID = newID
}
}
}
}
})
})
我正在使用 angularjs-ui-router 創建一個帶有聊天指令的父視圖,在該視圖中提供聊天。 這在第一頁加載時工作正常,聊天加載。 但是當我更改頁面/聊天室時,我使用另一個控制器來運行setCurrentChatID()
。 這會更改 DOM 中聊天元素的currentChatID
,我還看到聊天元素的屬性更改為 angularjs-batarang 中的新 ID,但聊天指令的控制器沒有運行。 當 chatID 更改時,如何使其正常工作/激活聊天的控制器?
謝謝。
如果沒有看到chat
控制器的其余代碼,很難說,但是您可能需要在聊天控制器中使用$watch
例如:
$scope.$watch('chatID', function(newValue, oldValue) {
// run some code here whenever chatID changes
});
編輯:有關$digest
循環和 Angular 的運行時操作的更多信息,請參閱此AngularJS 指南。 (檢查運行時部分)
有關控制器的更多信息,請參閱此AngularJS:了解控制器指南。 以下是與您的問題相關的要點:
控制器應僅用於:
$watch
等) $digest
循環僅處理:
$evalAsync
隊列$watch
名單
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.