【问题标题】:Angular ng show does not update while the scope doesAngular ng show 在范围更新时不会更新
【发布时间】:2015-03-14 11:53:11
【问题描述】:

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

聊天窗口有一个ng-show,取决于scope.openChat,即false。 当我单击按钮时,我将 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;
                });
            });
        }
    }
}]);

谢谢你

【问题讨论】:

  • MessagesCtrl 将有 2 个实例。你可以把它放在 rootScope 或其他方式中。

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


【解决方案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'};
}]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    相关资源
    最近更新 更多