Are controllers always awake? - javascript

I guess awake isn't the right word. Say I have a multi-page, large AngularJs application. Is the controller of a page that isn't active right now awake? For example, if I wanted to call a function of that controller with $rootScope.$broadcast, would it be listening for that signal or would it only recieve that signal when I go to the part of the page that requires that controller? Sorry if this makes not much sense.

Controllers have instances per usage, that means that angularJS will make an instance of some controller only if it is in use.
If you need to pass data from one controller to other, the common way is to use some service. As service are singletons which created on the first inject.
So, you can inject a service in one controller (page), invoke some method on it, which will change some data on it, then navigate to other page, in this page, inject the service, and use the data on it.

Related

How to pass data from one Javascript controller file to another?

So, the situation I have gotten myself seems to be a little complicated but I'm hoping there is a simple solution to it.
I have two Javascript controller files, one called rootPageClient.js and another called findPollClient.js. There is also a file called ajax-functions.js which basically contains two functions to route the ajax calls to the right route. The routes and the get and post method functions are contained in the index.js file. The file structure is shown below
Root
Common
ajax-functions.js
Controllers
findPollClient.js
rootPageClient.js
routes
index.js
I have a specific piece of data in the rootPageClient.js file that I need passed through to the findPollClient.js file. All calls are routed through the ajax-functions.js file to the requested route in index.js.
I have figured out that I need to call the same route in the index.js file from both controller files in the order that I want to pass the files from and to. But, I'm not quite sure how to do this. Is there a simple way to do this?
Create a service and save the data inside the service. Have the service injected in both the controllers. Whenever you change some data in service in one of the controllers, it will retain when you look it up in other controller. This is because services and factories are singletons, so they are the right place to store application state and access it anywhere you want.

Angular - async updates & rendering from service to controller

I have a Service that listens to webSockets (can't use callbacks or promises, data updates are random). service gets updates and saves them to service's object. I Have an angular-app page with controller that has the service object in the $scope.
But I got a problem in rendering data on the page. Right now I am using $timeout() to update the view but looking for a more elegant way.
I understand that I can use $watch on the service's object, but I think that it is too heavy for browser.
So what is the right way to render the view/controller after changes in service's data?
You can use $rootScope.$broadcast as an alternative but it's also as heavy as $watch, I don't know why you are afraid of using $watch, the cost in performance is not that big !!
To use $broadcast add this line of code to your service :
$rootScope.$broadcast('WatchedData', data);
And in your controller do something like the following :
$scope.$on('WatchedData', function(event) { return stuff });
to read more about $rootscope.$broadcast check this SO answer
i suggest you to use resolve , it will load data before controller and View is instantianting in your routing file , and inject your Service into function
You can watch this Demo PLunker Demo

How to pass parameter to function in AngularJS with promises

I wan to send parameter to service function.
getQuestions : function(stateCode) : questionResource.js
stateCode is set in $scope from the response of dtoResource.rc1Step1DTO()
angular
.module('autoQuote')
//Do initalization on page load
.run(['$log', '$rootScope', '$state', 'dtoResource', 'questionResource', function($log, $rootScope, $state, dtoResource, questionResource) {
$log.info('Post DTO on page load.');
dtoResource.rc1Step1DTO()
.then(questionResource.getQuestions)
.then(function(questions) {
$rootScope.questions = questions;
console.log('Obtained questions. Assigned to rootscope');
})
.then(function() {
console.log('This should be printed after the above methods are done executing');
console.log($rootScope);
});
}])
How to pass state code to the other function.
its position in scope is
$scope.postAutoQuoteObj.SessionInfo.StateCode
Below is the plunker for code
http://plnkr.co/edit/Op1QDwUBECAosPUC7r3N?p=preview
your module autoQuote.run() will only be called once during your applications loading. So don't expect to have it execute again.
you are close to the right answer. you just need to do some reorganization. One tip I would offer is to worry about creating a directive later, first get the controllers, routes working first.
You have created an excellent framework to start. you are using ui-router.
this means that you can tell ui-router what controller to execute when a state is requested. so the life cycle for your application is as follows
module.run //any code in here first. only on intial load
module.config //in your case app.config which creates your states.
then depending what state you are viewing based on the url;
the controller for that state (or view) will be executed
so if you add another state config for / you can bind that state to your autoQuoteCtrl.
additionally, there are a number of other issues, such as attempting to use ng-model and value in an input element. this is not correct.
you are not implementing your ui-views. this will mean your controllers will never execute. technically, it your case autoQuoteCtrl would be executed but only because you forced it onto the page using ng-controller, which is what ui-router is designed to avoid.
which I think is why you ended up placing your code in .run(). This was the only place you found your applicaton would "run" the code on page load which is false, it was only running because your app loaded. Sorry if I'm being redundant. But it is an important point.
Also, you are trying to access your json data by passing statecode to your resource. that is not how $resource works. you pass the name of the resource, and it will return everything at that resource. then you filter the code after the promise is returned. you only have one resource. that is "CA.json" so therefore you should be able to get away with only one line in your resource service and only need one resource service. You will need additional non-resource services that can do the heaving lifting of filtering out the correct data from the JSON. typically this is why an app would call out to different resources, so that each one returns the model needed, not a single monolithic resource.
and you should never ever ever be using document.getElementById() you are using angular, so you do not interact with the dom directly
finally, here is a much much revised plunkr to help guide you in the right direction.
http://plnkr.co/edit/dUJm01uu7RnhltC2pLLb?p=preview

How to pass data to one module to another module in angularJS

In my project I have two ng-app's one is for login page and another for home page.
Once login is successful for the user, in ajax success callback I got the some response related to that user and in that callback I am used the window.location="home.html".
As of now I used session storage feature to pass the data to home page.
The best way to do it is by creating a service. The service can be injected into your controllers and other services as necessary.
Create a service and use getter and setters.When you get a response in your first module set the object using setter and get the data using getter in another module.
The best way to communicate between two controllers or say two modules is using services.
According To angularjs examples only one module stands for one project though outof the box you can you can use more than one
but To Achieve this .This Is how i Normally model myproject
**MyProjectModule** (only **one** module)
---> loginController.js (initial page)
(If LOGIN IS Authorised Then Redirect To Desktop->desktopController.js)
---> desktopController.js
---> customerController.js
---> salesController.js

Angular service using $watch to do $http call when a property is changed

I'm pretty new to Angular and wondering what the best way to handle this is. My app is structured with a service that keeps track of the app state and currently loaded data. I inject this into all my controllers so the app state will be shared with them and can also be changed between controllers by using the service. The service is outlined a bit like this:
app.factory('AppStateService', function() {
return {
selected_section: "blog",
data_of_selected_section: {here_comes_data_from_an_api}
}
}
As said, I inject this in all my controllers and bind them to the controller scope, so they can all change those properties and this works perfectly. However, I'd really like the service to automatically do an $http call to an API, whenever some of the properties change. When the data comes back from the API, I want this data assigned to a property so the controllers can update based on this data.
In the above example for instance, if a controller changes selected_section from e.g. "blog" to "main", I want the service to do the $http call and put the returned data in data_of_selected_section to let it propagate to the controllers. I could of course do this directly from the controller and push the result to the service from there, but then I'd have to replicate that code in each controller. Thus, I'd rather want the service to do it by itself.
What is the best way to do this? I guess I'll have to build in a $watch or $watchCollection somewhere in the service but I have a hard time wrapping my head around exactly how to do so. Especially since I could easily imagine that doing it the wrong way could kill performance.
On a side note, the reason I want to do it this way is because I'm doing data visualization and thus it is mostly my interface and not my data that will change. Thus, I'd really like to store my data and app state "globally" in a service. I don't know if it makes sense. Any help would be greatly appreciated!
You could use .run as this method will instantiate the service on every route change.
app.run(function ($rootScope, AppStateService) {
$rootScope.$on('$routeChangeStart', function () {
$rootScope.data = AppStateService.data_of_selected_section
});
});
You can write your http call inside the service as it will be automatically called whenever there is a change in the route

Categories

Resources