I'm trying to pass a json object just after redirecting to another page,
The problem is when I use $scope.data in order to save client, the problem is that after making the redirection the $scope.data is empty again
testProjectApp.controller('ClientController',
function EventController($scope, clientList, $window, updateClient){
$scope.editClient=function(client){
$scope.data=client;
$window.location.href = 'ClientDetails.html";
}
the controller is working on two pages
It depends on if you only want to use angular specific APIs or general methods are also acceptable. Consider the followings, which one better fits your situation, you may need to serialize/de-serialize the json object:
Some options:
Cookies
Session Storage
Local Storage
Use Url to pass the parameters
If it is a single page application, then you can just set it to a variable in a Service, and inject that service the controllers need the var. Basically a get, set
It would be a good idea to figure out the size of the json, and are there any limits and constraints first, then choose the suitable method.
Angular is used for SPA's - single paged applications. As soon as you redirect to another page, a new scope is created. I used local storage - here I asked and answered my question in reference to it - AngularJS help sharing data between controllers using $broadcast
So to be honest, this is a duplicate.
Related
I have to add functionality to an existing AngularJS application. I need to be able to pass an additional parameter to potentially any route of the angular application. (It's an email tracking ID)
I would like to use a querystring parameter if it's possible, without affecting the existing routing. Then have some code somewhere that checks for the querystring parameter (not sure about this part, some kind of global navigation listener?).
I'm not super familiar with angular. Do i need to mess with the routing and mess with code in the controllers, or is there some way I can code one global service to parse the querystring parameter regardless of the route?
I know I could create a service that uses $location to get the querystring parameter, but I would have to inject that service into every controller which seems kind of redundant.
Since this is an email tracking id I'm assuming that you just need to grab it once when the user first enters the site. It also looks like you're not looking for a super deep solution, so I'd suggest just grabbing it where the main module (your app) is first created and storing the tracking id as a property on your app.
There is a $locationChangeStart and $locationChangeSuccess event that fires on the $rootScope that you can bind to in a run block somewhere if you want to grab a query string from the route every time the page changes.
But if you're trying to keep track of that value throughout your entire application, once you get it from the server, you could store it on a service and inject it wherever you need it in your application. If you're trying to avoid injecting dependencies into your Angular app, then you're only going to hurt yourself, especially when it comes time to write tests. Your controllers shouldn't depend on things that aren't provided through your application's injector.
Use $location. It adds hashed query string params like "example.com/#?myParam=value"
Get query string params:
$location.search(); // gives you an object of params
Set query string params
$location.search('myParam', 'value'); // one at a time
$location.search({ // or pass an object
'first':1,
'second':2
});
Just be sure to inject $location in your controller/directive.
I know that you could use a service or an HTTP call to a database to get the data you want in a view.
And I know that you could access data in the URL as parameters or via the query string.
But what if you want to pass - 1) a lot of data, 2) that doesn't need to persist - into a view?
For example, I have a form for creating a Thing, and I want the user to be able to preview the Thing. I already have a show view for Thing, and there's too much to display for a modal or to display it on the same page.
It seems unnecessary to use a service, and definitely doesn't seem necessary to use a database.
It seems excessive to pass it in via the URL.
Maybe you could use $sessionStorage?
Thoughts? Is there a best practice here?
Using a service is in fact a good idea. The first "view" set the service data, the other get it.
Or, if that answers what you mean by "without persisting the data", you could simply emit the data from one view (controller/directive/service) to another.
View1:
$scope.$root.$broadcast('bigdata', data);
View2:
$scope.$on('bigdata', function(e, data) {
// Deal with the data which is garbage collected at the end of this callback
});
I am fairly new to Angular and trying to build an Angular application.
I have a lot of data that needs to be used by multiple controllers throughout the app. As I understand it, that is the perfect situation to use a service.
I am planning on storing this kind of data in services. For example I plan on having a users service which all controllers that need user data will inject.
I would like the users service to hold the master list of users and any controller that needs users to just use the one instance of service list.
I am having trouble envisioning the pattern though. I mean:
1) What is the standard way of having the service refresh its data from the server? I realize that I could just go and request the entire list of users every 10 seconds from the server but that seems kind of heavy weight...
2) Ideally I would like to be passing around only a single instance of each user. This way if it gets updated in the service, it is sure to be updated in all of the controllers. I guess the other option is to have the service broadcast an event every time it updates a user? or to use watchers?
3) What is the pattern by which the controllers interact with the service and filters? Do the controllers just request data from the service and filter it in the controller? The other option is to have the service do the filtering. If so how do I communicate the kind of filtering I need done to the service?
I think that by using some kind of solid pattern I can take care of alot of these issues (and more that I am sure will arise). Just looking for advice on some common patterns people employ when using singleton services.
Thanks in advance.
Answer to point 1. A service is just a singleton. How you store and refresh data into it has nothing to do with its nature. Not sure why you want all user data inside a service (unless you are building a user management app), but you could use several techniques like polling (eg. using $timeout ask for new users and append them to the existing ones) or push (eg. socket.io/signalR which will push you the payload of new users when available). This can be done both inside the service itself or by a controller that will add/remove data to the service (eg. a refresh users button in the UI)
Answer to point 2. You can bind/use the reference of the data inside the service directly into your controllers using a getter so that changes to the data are shown instantly (given that are two way binded, if not use events).
Answer to point 3. You can apply filters inside the controllers or in the view it self (not recommended). You can also have a function in the service where you pass the filter or filter params and get the filtered copy of the users collection back (since you will be using the users collection directly in many controllers at once you shouldn't modify that, unless that's desired). If you are reusing the same filters again and again across the controllers you can have a function for each filter that returns the filtered collection with a "hardcoded" filter. You can even have helper function in the service to help you assemble complex filters or have multiple copies of the collection already filtered cached(if you find you are using the same filter again and again)
In an Angular app, I want to keep a couple of variables "global". I chose localStorage as a persister for this. Advantage: on page refresh, the global "state" of the app is retained.
The service providing such a local storage
My question: what is the cleanest method to provide this locally stored data to every controller and further to the view? Do I have to remember to:
inject my local storage into every controller
in each controller, assign the local storage data to the controller's scope?
Further info:
For example: On login, I select the project ("On which project are you going to work today?"). this project should be a global variable.
The app is constructed in a way that the header section is served by controller A and the content area is served by controller B.
I then would have to inject the local storage data into controller A and B.
angular.module('app').controller('ControllerA', function ($scope, Session) ...y
And in both Controllers, I would have to provide the data to the corresponding view by:
$scope.session = $localStore.getData();
I do not like the fact that I have to think about these lines for each controller. Is this a clean and preferred way to have such global app data?
Remark: no need to have a dynamic binding. On the landing page, the user selects the project which is then persisted and can be retrieved read-only by all subsequent controllers. If the global variables would need to be dynamic, things would be different.
JSFiddle example: http://jsfiddle.net/Wr7LS/5/
I would suggest to put localStorage in angular-service wrapper and inject it in places where you need to use this data.
no need for rootScope.
Easiest way to use shared values between controllers is the RootScope variable. Every controller see it same values.
I have an app I am designing using node/mongo/angular, what I am not getting is how is the best way to get my data from mongo into my pages? I can use node, and thru my routes send back data from mongo with my template(hogan in this case), and bind using mustachejs. That works fine for most things. I have one screen that has a decent amount of drop down lists, to bind them for an edit scenario now seems a challenge. I would like to get them bound to an angular model and go about it that way. Is it better to get the data thru the route in node, then use something like ng-init and get it into angular? Or would I be better off not getting the data thru the route in node, and then using angular to perform a "get" request and bind that way?
From the documentation of ng-init, more precisely from the red warning alert at the top of the page...:
The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.
So no, do not use ng-init. While that can be a good strategy for lazy migrations from regular applications to single page applications, it's a bad idea from an architectural point of view.
Most importantly, you lose two things:
An API. The benefit of SPAs is that you have an API and that you're constantly developing and maintaining it, even before it has external users
A clean separation of concerns. Views are strictly limited to presentation, can be cached by the client and all data is transferred through JSON API endpoints.
I would say that the best way to get data from Mongo into your page, is as mnemosyn said, using an API.
Basicly, you can have your API route, f.ex '/api/data' configured and then it can be used by a angular service, (which can use ngResource to make things easier). Any controller that wishes to access this data can use the angular service to get it, do some stuff with it, and then update it using the same angular service.