Kevin MacDonald
Kevin MacDonald

Reputation: 680

Getting AngularJS directives to update

Trying to push my understanding directives in AngularJS to the next level. I've read the book and made a lot of progress, but this is stumping me a bit. I think there's a basic bit of key understanding I am still missing.

Let's say on a view I have two directives. The directives are side by side, not nested within each other. They do not share scope in any way (that I am aware of). Both directives inject the same service. Upon clicking an item in Directive #1 the click handler calls a function on the service that changes something within the service which Directive #2 should react to. For example, let's say I had a "Logout" directive and a "My Account" directive. Upon clicking on "Logout", I want the "My Account" directive to dim out, or perhaps have the text change to "Please log in". The "Logout" directive is calling myService.logout(), and the "My Account" directive scope is perhaps bound to myservice.someObj.isLoggedIn(). The isLoggedIn() function starts returning false when the click happens.

How can I get the second directive to know that something happened? Can I trigger a function call within the directive upon an important change happening? How do I set up the scope of the directive to do this?

Thanks!

Upvotes: 0

Views: 90

Answers (2)

Dexin
Dexin

Reputation: 73

In the Logout directive, you can use $scope.$emit to pass the message LOGOUT_TRIGGERED to a parent scope.

In the parent scope, use $scope.$on to listen to that message. On receiving that message, just dispatch the message HANDLE_LOGOUT to the Account directive via $scope.$broadcast.

In the Account directive, using $scope.$on again to listen to that HANDLE_LOGOUT message.

  • $scope.$emit sends message to all parent scopes
  • $scope.$broadcast sends message to all child scopes

Or you can check this EventDispatcher service: https://github.com/trochette/Angular-Design-Patterns-Best-Practices/blob/master/js/base/EventDispatcher.js

Upvotes: 1

SkyOut
SkyOut

Reputation: 390

In your directive you can have the "My Account" button watch the service for a change. You just need to do a

$scope.$watch(mysevice.someObj.isLoggedIn, function() {

   //do something

})

Alternatively you could also have the first button $scope.$broadcast once its logged out and have the second service watch for that broadcast using $scope.$on.

UPDATE

 app.directive('directiveName', function () {
     restrict: 'AE',
     link: function ($scope, element, attrs){
         $scope.$watch(myservice.someObj.isLoggedIn, function () {
             // do stuff
         }
     }
 });

Upvotes: 2

Related Questions