I am currently trying to make a website. My main (AngularJS) controller requests JSON data, filters it and pushes it into an array. Now I would like to use said array in a different javascript file and I can't wrap my head around how to do it.
I read the option to create a service multiple times now however I believe that this is specifically for passing variables between two controllers.
Moreover, the other options did not work out for me as well.
What is the best approach to this? Thanks a lot.
You can create global javascript variable which will be accessible to both your controller as well as other JS file. Now update its value from controller which will change it at global level.
Then in the next file just retrieve it.
Related
i just starting to learn angular JS a month ago. And found something difficult.
I have the following plunker http://plnkr.co/edit/nsu6Pj?p=info
<input id="tags" ng-keyup="complete()" ng-model="data"/>
selected = {{data}}
As you can see, there is a list of available tags. i want to pass the selected value in the index.html page to next.html page by clicking the button.
Actually i want pass not just 1 parameter. Just like md-autocomplete in angular material.
Here is the image for example parameters i want to pass
I hope you guys can help me :) Thanks.
Well, if you're passing multiple values, you can choose to hold your values in an array or an object. I personally would just set your complete function to push the values to an array.
Now, as for exchanging data - You have three options that I can think of:
create a service that allows controllers to communicate with each other. You could then use that service to set a variable in one controller (holding your tags) and then use same service in a different controller to get the value.
broadcast an event in one controller with $rootScope.$broadcast and then listen to the event with $rootScope.$on
Save the data to the browser's cookies with angular's $cookieStore.
Now the way your stuff is actually set up you're instantiating a new module and controller in each page so options 1 and 2 are out. Here's how I set up saving the values in the cookies.
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.
I have an app with two controllers where I want a change in one controller to affect (different) data stored in the other. tl;dr when I remove a category from the first controller, I want to edit any items in the second controller with that category, so that they will now be category-less.
As far as I can tell what I want is to use a service, but I feel it would be simpler if there were a way for me to simply edit the data inside the controller scope. So my questions are:
Is there a way to simply edit controller data or call controller methods from a service?
Otherwise, is it reasonable to store the latter controller's data in the service, even though the former controller only needs access to change it? How do I reference this data for the purpose of doing ng-repeats?
Edit: to clarify the data is a set of json objects which contain data for each category and each item, and the web page contains ng-repeats to go through and list each of them. I have a number of functions which edit both lists of data, and I want changes to one list to make changes in the other.
Your idea was correct, you should put all your business logic, including data that needs to be consistent between different parts of your application, into services. controllers should only manage the view and connect the data to it.
Keep in mind that services are Singletons - there is always only one instance of each service, holding your data.
To answer your question: I would argue that storing data in a service instead of a controller is always reasonable when it works (aka when the data is not specific to one of multiple views, but consistent throughout the current application state), and giving access to that data to manipulate it is perfectly fine - even better would be to put the manipulation logic into the service itself (or another service only for that) and to just let the controller connect to a call invoking that.
There is an article by Todd Motto on that topic (thin controllers)
I think it will be better use events for this purpose. In your first controller you can published the event on category deletion like below.
$scope.deleteCategory = function (category) {
$rootScope.$broadcast("categoryDeleted", category);
}
Then you can observe this event in any controller like below in second controller you can listen categoryDeleted event.
$scope.$on("categoryDeleted", function (event, category) {
// do whatever you want
});
Do not call controller directly from the service, this is a bad practice, not only in AngularJS, but in most languages frameworks.
The problem you have described ("a change in one controller to affect (different) data stored in the other") is a problem of communication between components. You can solve this issue with events, thus there is no need to move data from the second controller to the service.
Let's consider some example:
http://jsfiddle.net/simpulton/XqDxG/
When you click on the LOG button the this.broadcastItem() is invoked, and the 'handleBroadcast' event is broadcasted.
Other constrollers, controllerOne and controllerTwo, handle this event:
$scope.$on('handleBroadcast'
and do the things they want to do.
So, in yor case, you can introduce the 'categoryRemoved' event, and broadcast this event in the first controller. Once the event is broadcasted, your second controller handle it and edit its items.
Also you should pass the removed category in the event (instead of 'msg' in the example), so that second controller has to aware which exactly category has been removed.
In way you want to do that, $rootScope can be used (shared across controllers - modyfing in one, accessing in another), but its generally bad idea. Im not sure if I get it right but its typical situation when you actually need service with controlling some external data.. Its some static json you want to modify? Can you specify it more clearly ? :)
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.
I have two javascript files in one folder.I want to pass a variable one javascript file to another.what procedure should I use?
window.postMessage is used for cross document messages. Use those messages to share data.
Question is bit confusing,
If the 2 javascript files are in 2 different pages you can use a query string to pass the values.
If both of them are in a single page the value can be simply passed using a variable. Simply define the variable int he first called script file or in the page. It can be accessed from any other javascript in the page defined below the first script.