Change ng-show in another controller? - angularjs

I want to change ng-show in another controller than ng-show is.
myApp.controller('popupCtrl', function() {});
myApp.controller('changePopup', function($rootScope){
// now i wanna show my Ppopup
$rootScope.popup = true;
});
<div ng-controller="popupCtrl">
<div ng-show="popup">
Popuptext
</div>
</div>
But this doesn't work... How can I fix it?
Thanks!

So first thing, you should never add to the $rootScope or change it in anyway. It has been optimised by the angular team.
Second thing, there is no need to involve the $rootScope.
Here is a demo showing how to communicate across two controllers.
The key is the event aggregator pattern:
Communicator.register(function (newValue) {
vm.value = Communicator.value;
});
I created a function in the Communicator to register a callback function. The aim is that when a value gets changed the callback function is fired off. I.e. an event is triggered (change event).
The second key part is fire that change event off:
Communicator.change(!Communicator.value);
Here we pass through to the change function a new value which will do two things:
Update the internal value so we can keep track of it
Loop through all the registered callbacks and execute them passing in the new value.
By implementing this pattern, we can minimise the extent to which we communicate around our application ($rootScope can have a tendency to traverse the scope heirarchy when you $broadcast).
Now we can follow more closely the principle of single responsibility. Our class is aptly named in its current scope, when we look at this factory we can tell it is supposed to "communicate".
Finally, with a global event aggregator pattern ($rootScope) it is far more difficult to keep track of where these events are being broadcast from, and where they'll end up. Here we don't have that issue

One way to solve this is to use $rootScope.$broadcast
Here is an example: http://plnkr.co/edit/EmJnZvXFRWv6vjKF7QCd
var myApp = angular.module('myApp', []);
myApp.controller('popupCtrl', ['$rootScope', '$scope', function($rootScope,$scope) {
$scope.popup = false;
$rootScope.$on('changePopup', function(event, data) {
$scope.popup = !$scope.popup;
});
}]);
myApp.controller('changePopup', ['$rootScope', '$scope', function($rootScope, $scope) {
$scope.changePopup = function() {
$rootScope.$broadcast('changePopup', 'data could be sent here');
}
}]);
View:
<div ng-controller="popupCtrl">
<div ng-show="popup">
Popuptext
</div>
<div ng-controller="changePopup">
<button ng-click="changePopup()">Change the popup</button>
</div>
Using a service/factory is a better solution for cross controller communication if you are working on a large application, but for a smaller app I would say using $broadcast, $emit and $on is sufficient.

Here is a working demo for you - sorry I changed the controller names, but I am sure you will be able to build on this. Good luck
angular.module('myApp', [])
.controller('c1', function($scope) {
// now i wanna show my Ppopup
$scope.popup = false;
$scope.$on('popup', function() {
$scope.popup = true;
});
})
.controller('changepopup', function($rootScope, $scope) {
// now i wanna show my Ppopup
$scope.clicker = function() {
$rootScope.$broadcast('popup')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="c1">
<div ng-show="popup">
Popuptext
</div>
</div>
<button ng-controller="changepopup" ng-click="clicker()">Click me</button>
</div>

Related

AngularJS | Handling $broadcast & $on for specific instance of the same controller

I have a utility controller build to manage documents attachments for reusing across my application.
<div ng-controller="someController">
<div ng-controller="documentController as temp1"></div>
<div ng-controller="documentController as temp2"></div>
</div>
Under the parent controller i.e. someController I have a broadcast method..
var module = angular.module("MyModule");
module.controller("someController",
function ($scope) {
$scope.$broadcast("callSomeFunctionInDocumentsController");
});
module.controller("documentController",
function($scope) {
$scope.$on("callSomeFunctionInDocumentsController", function() {
//do something here
});
});
Now the problem I am facing is that since the documentController is added twice to the view, the $on method is executed twice as well. Whereas based on some condition I would want to call the $on method either in temp1 or temp2 instance and not both.
I am not sure if what I wish to achieve is possible but any help will be much appreciated.
Thanks.
The $broadcast works simply: everyone who registered is notified through $on.
In your example, both controllers are registered.
So why do you use the same controller twice? Maybe worth to switch to component?
What about this one:
<div ng-controller="someController">
<div ng-controller="documentController as temp1"></div>
<div ng-if="oneCtrlGotNotification" ng-controller="documentController as temp2"></div>
</div>
where oneCtrlGotNotification is some flag (maybe under $rootScope).
So you will display second controller only when 1st already notified.
But it is a workaround.
One approach is to give a unique id to each element with a controller:
<div ng-controller="someController">
<div id="temp1" ng-controller="documentController as temp1"></div>
<div id="temp2" ng-controller="documentController as temp2"></div>
</div>
Then use the $attrs local to differentiate:
app.controller("documentController", function($scope, $attrs) {
$scope.$on("callSomeFunctionInDocumentsController", function() {
if ($attrs.id == "temp1") {
//do something specific to "temp1" controller
});
});
})
For more information, see
AngularJS Comprehensive Directive API Reference - controller
AngularJS $attrs Type API Reference

Ionic - AngularJS: calling methods via template outside of Controller

So, here's a sample code:
<div ng-controller="MyControllerOne">
<span ng-click="foobar()">Click Me!</span>
</div>
Can I, from that template, without changing controller, call the function foobar() in MyControllerTwo:
.controller('MyControllerOne', function($scope) {
//some code
})
.controller('MyControllerTwo', function($scope) {
// method I wanna call
function foobar(){
}
})
While not the prettiest solution, it is technically possible...ish.
If you update your HTML to:
<div ng-controller="MyControllerOne">
<span ng-controller="MyControllerTwo as mct" ng-click="mct.foobar()">Click Me!</span>
</div>
Then you should get your expected results.
You can call method which is in another controller from the template by injecting '$controller' service in the controller. Below is the demo and code.
You can see demo here: http://plnkr.co/edit/oBEKxamgJv0uDVsJJwth?p=preview
HTML:
<body ng-controller="MainCtrl">
<div ng-click="fooBar()">Click Me!</div>
</body>
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $controller) {
$controller('SubCtrl', {$scope: $scope});
});
app.controller('SubCtrl', function($scope) {
$scope.fooBar = function() {
alert('second controller');
};
});
Pretty old question, but if any one is still looking for an alternative answer ...
It should be possible to use $emit or $broadcast.
Like from ControllerOne :
$rootScope.$broadcast('callToFoobat',{});
And then from ControllerTwo :
$scope.$on('callToFoobat', function(){
// whatever you want, so why not a call to foobar
})
Just a rough solution. Might be more elegant or lighter than just $rootScope.$broadcast. And maybe think about stoping propagation whenever needed.

Manage ng-if from another controller

I have prepared a Plunkr that provides the code:
https://plnkr.co/edit/WXtQxVcdgyvnaajbs4eJ?p=preview
I have assigned the object $scope.menu.show in controller toolbarCtrl that controls whether the menu is created or not.
<md-menu id="menu" ng-controller="toolbarCtrl" ng-if="true"> ...
When toolbarCtrl gets initialized I can control whether the menu is shown but I would like to control it from another controller. In this case I created two buttons in mainCtrl that produce true or false and I'm trying to assign the value to the $rootScope but that doesn't work.
How can I do that?
UPDATE:
Although jtmingus solution works perfectly I came up with another solution that doesn't need events.
I created this factory service:
app.factory('menuState', function () {
var state = {val: false};
function getState() {
return state;
}
function setState(newState) {
state.val = newState;
}
return {
getState: getState,
setState: setState
}
});
Then at the toolbarCtrl controller I initially hide the menu
app.controller('toolbarCtrl', function($scope, menuState) {
// hide the menu
menuState.setState(false);
// pass the value to the menu
$scope.state = menuState.getState();
});
on the mainCtrl I define the button clicks like that:
app.controller('mainCtrl', function($scope, $rootScope, menuState) {
$scope.state = menuState.setState;
});
and 2 buttons on the the main.html
<md-button class="md-primary md-raised" ng-click="setState(true)">Show</md-button>
<md-button class="md-primary md-raised" ng-click="setState(false)">Hide</md-button>
The way that data generally should be shared through controllers is by using a service. Because you need both controllers to watch the same state, you can use Angular's events, specifically the $on event.
Here is an article that will walk you through having multiple controllers watch the same state:
https://variadic.me/posts/2013-10-15-share-state-between-controllers-in-angularjs.html
Edit: After looking through this article some more, I realized it's not the best explanation, and there are some things in the code that don't work. For example, if you try to pass arguments in with a $broadcast call, the $on function needs two paramaters–event and args.
On the controller from which you want to initiate showing the menu,
app
.controller('MainCtrl', ['$scope', function($scope) {
$scope.$broadcast('menu:show');
}])
.controller('ToolbarCtrl', ['$scope', function($scope) {
var ToolbarCtrl = this;
$scope.$on('menu:show', function() {
ToolbarCtrl.showMenu = true;
});
}])
In the markup switch using this value
<md-menu id="menu" ng-controller="ToolbarCtrl" ng-if="ToolbarCtrl.showMenu"> ...

Why does not work two controller in Angular JS?

I have controller is named "UserController" in top of page:
<div ng-controller="UserController"><input type="text" ng-model="search"></div>
Also the same controller in bottom page from directive ng-view:
<div class="bottom" ng-controller="UserController">{{search}}</div>
Why I dont get value {{search}} in bottom part, when I fill field input in top?
Can I use one controller two times in a page?
Yes, you can use two controllers in AngularJs, Here is a demo.
What happens when I use ng-controller?
When you add ng-controller to a DOM element, angular create an instance of controller function and attaches it with that DOM, and thats why there is no two way data-binding between those divs.
How can I use data binding to share data between controllers?
You can use $rootScope variable or you can use services.
you can create service and inject in controller as dependency, so you can access its property with two way binding feature.
As said by JB Nizet, you need to have everything in the same "div".
<div ng-controller="UserController">
<input type="text" ng-model="search">
<div id="search-query">{{search}}</div>
</div>
Having the search-query at the bottom of the page is a matter of CSS, not Angular.
Controllers are not singletons. You have one controller for the top div, a second controller for the second div. One scope for the top div, one scope for the bottom div.
Both controllers have the same name, but you are ultimatally calling you controller function twice.
Some options you might want to consider to solve your problem:
Option 1) Use parent scope.
ng-model="$parent.search"
{{$parent.search}}
Option 2) Use root scope.
ng-model="$root.search"
{{$root.search}}
Option 3) Store the value in a service.
Services are singletons. If you type myService.search = $scope.search, then that value can read from the other controller.
You wont be able to watch a service variable, so perhaps you want to use the observer pattern here.
app.service("search", function() {
var listerners = [];
this.register = function(listener) {
listerners.push(listener);
};
this.update = function(searchValue) {
for(var i in listerners) {
listerners[i](searchValue);
}
};
});
app.controller("UserController", function($timeout, search){
search.register(function(searchValue) {
$timeout(function(){
$scope.search = searchValue;
});
});
$scope.$watch('search', function (newVal, oldVal, scope) {
search.update(newVal);
});
});
Option 4) Broadcast the new value.
$scope.$watch('search', function (newVal, oldVal, scope) {
$rootScope.$broadcast('search', newVal);
});
$scope.$on('search', function(event, data) {
$scope.search = data;
});
You can have multiple instances of the same controller in your page. They share the same functionality. But every instance of that controller is getting his own $scope. So in your first controller $scope.search can be 'mySearch', but the second controller won't get this, because it's another $scope.
You can do two things:
You can put the controller on a containing element, let's say the body, so both your input and your div are within the same $scope.
OR, if you want them to be seperate, you can use a service to share the search.
Your HTML:
<div ng-app="myApp">
<div ng-controller="UserController">
<input type="text" ng-model="search.mySearch"/>
</div>
<div ng-controller="UserController">
{{search.mySearch}}
</div>
</div>
Your Javascript:
var myApp = angular.module('myApp', []);
myApp.factory('Data', function(){
return { mySearch: '' };
});
myApp.controller('UserController', function( $scope, Data ){
$scope.search = Data;
});
See Fiddle

how to broadcast and emit events to other controllers in angular that have no parent-child relationship

I am trying to get hints from this post - Working with $scope.$emit and $scope.$on but nothing seems to work when the controllers are in no way related to each other.
That is -
<div ng-controller="CtrlA">
</div>
<div ng-controller="CtrlB">
</div>
and in CtrlB I would do something like this:
$rootScope.$broadcast('userHasLoggedIn', {})
and in CtrlA I would listen like so:
$rootScope.$on('userHasLoggedIn, function(event, data){});
And no - CtrlA never receives the broadcasted event unless I nest CtrlB div inside CtrlA div
Any idea?
It is tough to answer without knowing what you tried. Please see this plnkr:
http://plnkr.co/edit/hYzWOrgEyPLlCMZnDCo2?p=preview
I basically created two controllers, one sends some text to the other:
app.controller('CtrlA', function($scope, $rootScope) {
$scope.submit = function(){
$rootScope.$broadcast('userHasLoggedIn', $scope.input);
}
});
app.controller('CtrlB', function($scope) {
$scope.$on('userHasLoggedIn', function(event, data){
$scope.data = data;
});
$scope.data = 'nothing';
});

Resources