范围确实不会更新Angular ng show

时间:2015-01-15 22:46:55

标签: javascript html angularjs angularjs-directive angularjs-scope

我正在设置一个应该打开聊天窗口的<button>

聊天窗口的ng-show取决于scope.openChatfalse即可启动。 当我单击按钮时,我将scope.openChat更新为true并使用$scope.apply。 范围似乎已更新,但ng-show没有做任何事情。

这是html

<div ng-controller="MessagesCtrl">
    <button start-chat>Send Messages</button>
</div>

<div ng-show="openChat" ng-controller="MessagesCtrl">
    <div>CHAT WINDOW
    </div>
</div>

这是控制器:

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;
                });
            });
        }
    }
}]);

谢谢

1 个答案:

答案 0 :(得分:1)

我建议不要创建MessagesCtrl的两个实例。以下是您尝试解决的问题的简化工作示例。检查标记,看看MessagesCtrl包含这两个元素。否则,您正在更新$scope并致电$apply

另请注意,.on().bind() jQuery docs

的首选方法

JSFiddle Link

<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'};
}]);