简体   繁体   中英

Angularjs Can I change $scope value of a controller from another controller?

I have an HTML div , like

<div id="loader-container" data-ng-controller="LoaderController" ng-show="shouldShow">
Some html design
</div>

And in my controller

angular.module('core').controller('LoaderController', ['$scope','$location', 'Authentication', '$rootScope',
function($scope,$location, Authentication, $rootScope) {
    $scope.shouldShow = true;
}

]);

And now, I want to hide that html div from another controller, That's why I tried to make $scope.shouldShow variable as false from another controller. So how can I make

$scope.shouldShow = false;

from another controller. Is it possible or any alternative way.?

every controller will create a new Scope.

Hence the changing the scope in one controller will not reflect in the scope of other controller.

If you want to share a property across the controllers create that variable on the $rootScope and use it.

In Controller

$scope.$root.shouldShow = true; //or false

In Markup

<div ng-show="$root.shouldShow"></div>

It's not a good idea to manipulate a $scope of a controller from a different controller directly. It would make your controllers very tightly coupled.

One commonly accepted way to communicate between controllers is through messages using the publish-subscribe pattern .

If your controllers are in completely separate components and you just need to notify the other controller, you can use the $broadcast/$emit and $on methods of the scope object to broadcast a message from one controller and listening to a specific message in a different controller. When an action happens that should change the shouldShow variable, you can just broadcast a message and make the other controller listen and act on it.

Root Scope API

Another common way to communicate between controllers is by using angular services , acting as a mediator between controllers.

If your controllers are part of the same component/module, and you need to share state/behavior between those, then using an angular service to encapsulate that logic and expose it would be an OK approach (services are singletons in Angular). That would be pretty simple to implement.

However, not knowing more details about your exact requirements, it's hard to design a proper solution.

Thanks to @Callum Linington for discussing the alternatives in the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM