$rootScope $broadcast working on two different controllers - javascript

I am trying to build a single page application where I have a setting form where I add a variable called Ticket Work type. When I do an update or save on the setting form, I am broadcasting the new Ticket Work Type array so that it reflects the listing as well as Ticket create page.
But the problem is that broadcast works only on the settings form page controller and not on the Ticket Add controller.
This is the code from the Settings controller where after "addTicketWorkTypes" factory method, I do a broadcast. This works :
$scope.addNewTicketWorkType = function(newticketWorkType) {
if (newticketWorkType != '') {
ticketFact.addTicketWorkTypes(newticketWorkType, $scope.workspaceId).then(function(response) {
$rootScope.$broadcast('handleTicketWorkType',response.data);
ticketFact.ticketWorkType = '';
});
}
};
And this updates the list on the same controller
/*update ticket work type when changes at any place*/
$scope.$on('handleTicketWorkType', function(events, ticketWorkType) {
$scope.ticketWorkType = ticketWorkType;
console.log('Scope updated settingsEditCtrl');
});
But the same $scope.$on doesn't work on a different controller. Can you please help.
The whole code is on Github for reference as well:
The settings controller is here: https://github.com/amitavroy/my-pm-tools/blob/master/public/assets/js/dev/settings/controllers/settingsEditCtrl.js
and the Ticket Add screen controller is here: https://github.com/amitavroy/my-pm-tools/blob/master/public/assets/js/dev/tickets/controllers/ticketAddCtrl.js

Any given scope will only be notified of events that are broadcast from a scope higher in the inheritance hierarchy. To send an event up the hierarchy use $rootScope.$emit().
If you want to be sure the event will be sent and received and you're not worried about other scopes responding to the event, you can do this:
function $broadcast() {
return $rootScope.$broadcast.apply($rootScope, arguments);
}
...
$broadcast('handleTicketWorkType', response.data);
In your other controller:
$rootScope.$on('handleTicketWorkType', function(data) {...});
If that doesn't work
It must be (as suggested by #charlietfl) that the target $scope does not yet exist and is hence not being notified of the event. In that case create a ticketWorkTypes service that is nothing but a list of ticketWorkTypes. Then replace:
$rootScope.$broadcast('handleTicketWorkType',response.data);
with
ticketWorkTypes.push(response.data);
Then inject ticketWorkTypes service (array) into any controller that needs that data.

Related

How to pass Data from One Controller to Service and access that data on Other Controller on same event?

I'm facing some issue while trying to pass the data from one controller to the other using my service.
I've been implementing the prototype inheritance using the $rootScope in my controller and broadcasting that object, so that I can access that data in the other controllers.
As I'm using the $rootScope, I'm polluting the global namespace, I'd like to pass the data from this controller to the other.
I'm just displaying minimal data inside a table, when the user clicks on specific record of the table, I want to display entire data inside the object.
This is how I'm handling.
<tr ng-repeat="contact in filterContacts = (contacts.contactsData | filter:sensitiveSearch | orderBy:selectBox) " ng-style="{'background-color': contact.email == selectedContact.email ? 'lightgrey' : ''}" ng-click="selectContact(contact)">
In Controller A: I'm calling this function from view and injecting the specific row contact detail.
$scope.selectContact = function(contact) {
contactService.selectedContactInfo(contact);
};
In the Service I'm just returning that data -
var selectedContactInfo = function(contact) {
return contact;
};
How can I access this data in the Controller B during the same event and display it on my view.
Here is the reference Link: http://plnkr.co/edit/beOmiv?p=info
I don't want to use the $rootScope, but I'd like to access the data onto the other controller.
You could use an angular service for this.
The angular services are singletons and you inject them in controllers so you could inject the same service in two different controllers and you are effectively passing state between them.
Imagine you have a property in your service which could be called selectedUserID. You update this property when you click on the specific row. Then in the next controller, you inject the same service and use this property to determine which details you will load.
so you could have a method inside your service which could look like this :
updateSelectedUser = function(userID) {
this.selectedUserID = userID;
}
Your controller then calls this method from the service when the click action happens :
myService.updateSelectedUser($scope.selectedUserID);
This is just an example of course, put your own values in there.
One thing to keep in mind : services can hold state, they are objects after all and singletons so you always inject the same instance.
It makes sense to make sure that the state stored inside the service is not modified by outside actions which do not go through this service. In other words make sure that nothing else changes this selectedUserID so your service state data never gets out of sync. If you can do this, then you are golden.

How service can know when the controller who injected it has destroyed?

I have a books service to search for book.
Most of the time the service, give for example only 20 books.
I want the service to be able to change properties of the books on the screen, after the controller recieve the data.
For example:
I have a controller that show list of 20 books (from a search query, and limit properties).
I want that the service will be able to change the books that the controller got, after the controller got the data (realtime change)
controller($scope,bookService){
$scope.data=bookService.getList(query,20)
}
service(function(){
var dataBindedToController=[]
return{
getList:function(query,limit){
dataBindedToController.push([{name:'book1'},{name:'book2'}])
return dataBindedToController[dataBindedToController.length-1]
}
}
})
In the example above every time controller ask for list of books I add the returned data to the service by reference. After that for example if I do in the service: dataBindedToController[0][2].name='Moshe', it will automatically update the controller. the Controller $scope.data === dataBindedToController[0]
Now the question is: When the controller have destroyed, how the service can now this, and remove the bindedData from it's array?
I want to keep the controller ASAP (as simple as possible).
Another example:
A working JSFiddle, that use the bind technique to update a counter in a service, after the controller got the data:
https://jsfiddle.net/tLLtn45j/
var app=angular.module('app',[])
.controller('a',function($scope,service){
$scope.data=service
})
.service('service',function($interval){
var data={counter:3}
$interval(function(){data.counter++},500)
return data
})
The question is: how the service can now when to stop update the counter, when the controller have been destroyed
You can pass the scope like this
controller($scope,bookService){
$scope.data=bookService.getList($scope, query,20)
}
then save the $scope in your service, then attach the event listener there. I'm not sure though if it's a good practice to pass the $scope to the service, and I think it's not
you can listen to $destroy event
$scope.$on('$destroy', function() {
bookService.destroy($scope.$id);
})
you might want to index the dataBindedToController with $scope.$id so you will know what to remove

Angularjs Best Practice for Data Store

My angular app have 2 controllers. My problem is that the controllers does not keep the data when the user navigates away from the page.
How can I store the selected data on of my controllers into a data store so it can be used between other controllers?
Option 1 - custom service
You can utilize a dedicated angular service to store and share data between controllers (services are single instance objects)
service definition
app.service('commonService', function ($http) {
var info;
return {
getInfo: getInfo,
setInfo: setInfo
};
// .................
function getInfo() {
return info;
}
function setInfo(value) {
info = value;
}
});
usage in multiple controllers
app.controller("HomeController", function ($scope, commonService) {
$scope.setInfo = function(value){
commonService.setInfo(value);
};
});
app.controller("MyController", function ($scope, commonService) {
$scope.info = commonService.getInfo();
});
Option 2 - html5 localStorage
You can use the built-in browser local storage and store your data from anywhere
writing
$window.localStorage['my-data'] = 'hello world';
reading
var data = $window.localStorage['my-data']
// ...
check out this awesome project:
https://github.com/grevory/angular-local-storage
Option 3 - via web server api
If you need to persist data among different users, you should save it somewhere in the server side (db / cache)
function getProfile() {
return $http.get(commonService.baseApi + '/api/profile/');
}
function updateProfile(data) {
var json = angular.toJson(data);
return $http.post(commonService.baseApi + '/api/profile/', json);
}
EDIT See Jossef Harush's answer where he has written an in-depth response that covers other methods including this one.
I'd recommend using either localStorage or sessionStorage - http://www.w3schools.com/html/html5_webstorage.asp.
HTML local storage provides two objects for storing data on the client:
window.localStorage - stores data with no expiration date
window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)
This assumes that you don't want to POST/PUT the data to your web service (windows service mention in your question).
If you data is an array or some sort, you can convert it to JSON to store as a string and then when you need it you can parse it back as follows - How do I store an array in localStorage?:
var names = [];
names[0] = prompt("New member name?");
localStorage["names"] = JSON.stringify(names);
//...
var storedNames = JSON.parse(localStorage["names"]);
There is an option not mentioned in other answers (AFAIK).
EVENTS
You can use events for communication between controllers.
It's a straightforward communication that doesn't need a mediator
(like service) and can't be wiped by the user (like HTML storage).
All the code is written in controllers that you are trying to
communicate with and thus very transparent.
A good example how to leverage events to communicate between controllers can be seen below.
The publisher is the scope that wanna publish (in other words let others know something happened). Most don't care about what has happened and are not part of this story.
The subscriber is the one that cares that certain event has been published (in other words when it gets notified hey, this happened, it reacts).
We will use $rootScope as a mediator between publisher and a subscriber. This always works because whatever scope emits an event, $rootScope is a parent of that scope or parent of a parent of a parent.. When $rootScope broadcasts (tells everyone who inherits) about an event, everyone hears (since $rootScope is just that, the root of the scope inheritance tree) so every other scope in app is a child of it or child of a child of a child..
// publisher
angular.module('test', []).controller('CtrlPublish', ['$rootScope','$scope',
function ($rootScope, $scope) {
$scope.send = function() {
$rootScope.$broadcast('eventName', 'message');
};
}]);
// subscriber
angular.module('test').controller('ctrlSubscribe', ['$scope',
function ($scope) {
$scope.$on('eventName', function (event, arg) {
$scope.receiver = 'got your ' + arg;
});
}]);
Above we see two controllers communicating a message to each other using an event. The event has a name, it has to be unique, otherwise, a subscriber doesn't differentiate between events. The event parameter holds autogenerated but sometimes useful data, the message is the payload. In this example, it's a string but it can be any object. So simply put all the data you wish to communicate inside an object and send it via event.
NOTE:
You can avoid using root scope for this purpose (and limit the number of controllers that get notified of an event) in case two scopes are in direct inheritance line of each other. Further explanation below:
$rootScope.$emit only lets other $rootScope listeners catch it. This is good when you don't want every $scope to get it. Mostly a high level communication. Think of it as adults talking to each other in a room so the kids can't hear them.
$rootScope.$broadcast is a method that lets pretty much everything hear it. This would be the equivalent of parents yelling that dinner is ready so everyone in the house hears it.
$scope.$emit is when you want that $scope and all its parents and $rootScope to hear the event. This is a child whining to their parents at home (but not at a grocery store where other kids can hear). This is a shortcut to use when you wanna communicate from the publisher that is a child or n-th child of the subscriber.
$scope.$broadcast is for the $scope itself and its children. This is a child whispering to its stuffed animals so their parents can't hear.
EDIT: I thought plunker with a more elaborate example would be enough so I decided to keep is simple here. This elaborate explanation should be better.
To share data between two controllers on the same page, you can use factories/services. Take a look at Share data between AngularJS controllers for example.
However, if this is across page reloads/refreshes, you will need to store the data in local storage and then read it upon reloading. An example of that is here: How do I store data in local storage using Angularjs?
Checkout this library https://www.npmjs.com/package/angularjs-store
This can help you manage your application state much simpler as it will force you to have a one way data flow on your application.

angular how to use scope from a different controller

I have a user.list.ctrl and a user.detail.cntr. All the controllers are build as a module and are injected in a "user-module" which I inject in the app.js. (see the complete code in the plunker below)
my controller module
angular.module('user-module', ['user-module.controllers']);
my user-module
angular.module('demo.app', ['user-module']);
In both controllers i inject user-Fctr with data from a REST factory. (works well)
user.list.cntrl has a $scope.refresh()
user.detail.cntrl has a $scope.update()
user.list.cntrl
When I enter a new record, i call the $scope.refresh() so I can refresh the list. (this is working fine)
user.detail.cntrl
When i click a user from the list, the user detail loads in a different view (works ok)
when I update the user.detail, I want to call $scope.refresh() to update the user.list , but it is not working. I cannot call $scope.refresh()
I thought that since I inject the same factory into both controllers I can use each others $scopes.
Any ideas on how I can use $scope.refresh() (or update the list when I update the user.detail.js)
I make a plunker with all the js files (the plunker is not functional, it is only to show the code that I have)
http://plnkr.co/edit/HtnZiMag0VYCo27F5xqb?p=preview
thanx for taking a look at this
This is a very conceptual problem.
You have created a controller for each "piece" of view because they are meant for different activities. This is the purpose of controllers. So that is right.
However, you are trying to access the refresh function, written in one controller, in another one. Taken literally, this is wrong, since then, refresh is out of place either inside the user list controller or the detail controller.
A function that is meant to control (literally) what is happening on a specific piece of view is a controller. - There you are right having a controller for the list and one for the details.
A function that is meant to be shared between controllers must be a service. This is exactly what you want for your refresh function to be.
Whenever you inject the same factory into n controllers, you can't use the scope of every controller. This isn't the purpose of a controller.
However, whenever you inject the same factory into n controllers, you can use its exposed methods.
The problem you have, can be solved as follows:
app.factory( 'sharedFunctions', [ 'factoryId', function sharedFunctions( factoryId ) {
var refresh = function () {
factoryId.getAll(/*your params to query*/)
.success( function ( response ) {
//This will return the list of all your records
return response;
});
};
return sharedFunctions;
}]);
With this factory service registered, then you can inject it to your controllers and whenever you need to refresh, just call the exposed method of the service and plot the new information into the view.
Hope it works for you!
i ended up doing this:
I added in the list.contrl this:
factoryId.listScope = $scope;
since I already have the factoryId (my data service) injected in the detail controller, I can call this:
factoryId.listScope.refresh();
it works but I don't know if this is the best way. any comments?

Clear $scope on logout in Angular js

In my controller I am storing data as $scope.$parent.dossierSummaries = data;
but after log out and login the application $scope.$parent.dossierSummaries retains the same old data.
I am doing this on log out
.success( function( response, status ) {
if ( response.status > 0 ) {
var u = $rootScope.user.username;
$cookieStore.remove('myapp');
$rootScope.user = { username: '', role: 0 };
success(u);
}
else {
error(response.messages);
}
})
.error( function( response, status ) {
error(['There was an error logging you out.']);
});
in angularJS, you shouldn't set the variable directly to a controller but you should retrieve it from a service instead. So whenever you load a controller you should write a init() function to get value of that model. So everytime you will have the correct data from server.
Code example and docs : http://docs.angularjs.org/guide/dev_guide.services.creating_services
Another approach to manually tracking and cleaning things up would be to broadcast a 'logout' event on the rootScope (or other custom event). Then listen for the event either in your controller or in your service to clean up the data.
Broadcast:
$rootScope.broadcast('logout');
Watching for an event (in a service for example):
$rootScope.on('logout',function(){
dossiers = [];
});
I don't think there is any effective way to achieve it. Any object (controller, directive,filter or as a matter of fact any js object) can hold reference to another object (in your case user), and one cannot determine easily who all are holding reference.
The reference would only get release if you do it either explicitly or when the object holder the reference is destroyed.
What you can try is
$rootScope.user.username='';
$rootScope.role=0;
Assuming some object are tracking this specific object the data would be cleared now.
if you don't mind a slight screen flickering on logout, you can refresh the page using a method like this:
$window.location.replace($window.location.toString().split('#')[0]);
this would clear out all the $scope and $rootScope variables, and in my case has solved the issue.
If you want to clear the $scope, I think you can use it's constructor method or proto (prototype), which is used in constructor. I believe you can do that to reset the scope to initial state. If someone knows any more on this, feel free to comment.

Categories

Resources