Ruben
Ruben

Reputation: 195

Angular ng show does not update while the scope does

I am setting up a <button> that is supposed to open a chat window.

the chat window has a ng-show depending on scope.openChat which is false to start. When I clicked the button I update scope.openChat to true and use $scope.apply. The scope seems to have updated but the ng-show does not do anything.

here is the html

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

and

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

here is the controller:

app.controller("MessagesCtrl", function MessagesCtrl($scope,Auth) {
    $scope.openChat = false;
    $scope.message = { recipient : undefined, sender: undefined, text:'text'};
});

Here is the directive for the button:

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

thank you

Upvotes: 4

Views: 8256

Answers (1)

scniro
scniro

Reputation: 16989

I'd suggest not creating two instances of MessagesCtrl. Here is a simplified working example of the issue you are trying to solve. Examine the markup and see that MessagesCtrl contains both of these elements. Otherwise, you were on the right track updating $scope and calling $apply

Also note that .on() is the preferred method to .bind() see 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'};
}]);

Upvotes: 1

Related Questions