我有一个聊天指令,用于在页面上放置聊天室。
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 创建父 View ,其中聊天指令在该 View 内提供聊天。这在第一页加载时工作正常,聊天加载。但是当我更改页面/聊天室时,我使用另一个 Controller 来运行
setCurrentChatID()
.这会改变 currentChatID
对于 DOM 中的聊天元素,我还看到聊天元素的属性更改为 angularjs-batarang 中的新 ID,但聊天指令的 Controller 不运行。当 chatID 发生变化时,如何让它正常工作/激活聊天的 Controller ?谢谢。
最佳答案
没有看到您的 chat
的其余部分,很难说 Controller 的代码,但您可能需要 $watch
在您的聊天 Controller 中,例如:
$scope.$watch('chatID', function(newValue, oldValue) {
// run some code here whenever chatID changes
});
编辑:更多关于
$digest
循环和 Angular 的运行时操作,参见 AngularJS Guide . (检查运行时部分)有关 Controller 的更多信息,请参阅 AngularJS: Understanding Controllers指导。以下是与您的问题相关的要点:
Controller 应仅用于:
$watch
等)$digest
仅循环处理:$evalAsync
排队$watch
列表 关于javascript - AngularJS 指令对属性更改没有反应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16641284/