Javascript 当作用域更新时,角度显示不更新
我正在设置一个Javascript 当作用域更新时,角度显示不更新,javascript,html,angularjs,angularjs-directive,angularjs-scope,Javascript,Html,Angularjs,Angularjs Directive,Angularjs Scope,我正在设置一个,用来打开聊天窗口 聊天窗口有一个ng show,具体取决于scope.openChat,开始时为false。 单击按钮后,我将scope.openChat更新为true并使用$scope.apply。 范围似乎已更新,但ng show没有任何作用 这是html <div ng-controller="MessagesCtrl"> <button start-chat>Send Messages</button> </div>
,用来打开聊天窗口
聊天窗口有一个ng show
,具体取决于scope.openChat
,开始时为false
。
单击按钮后,我将scope.openChat更新为true并使用$scope.apply
。
范围似乎已更新,但ng show
没有任何作用
这是html
<div ng-controller="MessagesCtrl">
<button start-chat>Send Messages</button>
</div>
以下是按钮的指令:
'use strict';
app.directive('startChat',[ 'Post', 'Auth', function (Post, Auth) {
return {
restrict: 'A',
replace: true,
bindToController: true,
controller: 'MessagesCtrl',
link: function(scope, element, attrs) {
element.bind('click', function() {
scope.$apply(function() {
scope.openChat = true;
scope.message.recipient = scope.profile.$id;
scope.message.sender = Auth.resolveUser().uid;
});
});
}
}
}]);
谢谢我建议不要创建两个
MessagesCtrl
实例。下面是您试图解决的问题的简化工作示例。检查标记并查看MessagesCtrl
是否包含这两个元素。否则,您在正确的轨道上更新$scope
并调用$apply
还请注意,.on()
是.bind()
的首选方法,请参见
MessagesCtrl将有2个实例。您可以将其放在rootScope或其他方式中。
app.controller("MessagesCtrl", function MessagesCtrl($scope,Auth) {
$scope.openChat = false;
$scope.message = { recipient : undefined, sender: undefined, text:'text'};
});
'use strict';
app.directive('startChat',[ 'Post', 'Auth', function (Post, Auth) {
return {
restrict: 'A',
replace: true,
bindToController: true,
controller: 'MessagesCtrl',
link: function(scope, element, attrs) {
element.bind('click', function() {
scope.$apply(function() {
scope.openChat = true;
scope.message.recipient = scope.profile.$id;
scope.message.sender = Auth.resolveUser().uid;
});
});
}
}
}]);
<div ng-app="app">
<div ng-controller="MessagesCtrl">
<button start-chat>Send Messages</button>
<div class="chatWindow" ng-show="openChat"></div>
</div>
</div>
app.directive('startChat', [function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.on('click', function() {
scope.$apply(function() {
scope.openChat = true;
});
});
}
}
}]);
app.controller('MessagesCtrl', ['$scope', function($scope) {
$scope.openChat = false;
$scope.message = { recipient : undefined, sender: undefined, text:'text'};
}]);