AngularJS pass data from controller to another controller - javascript

What I have done.
I retrieve a list of videos from youtube api with json in a controllerA with specific directive. The json contain the list of video and the video itself details.
What I want to do.
When click on a video, I want the video's details display in another ng-view with other controllerB with using the json data I request before.
So my question is
How to pass the data from controllerA to controllerB
Note - $http service is use in controllerA

This is one of the common doubts when starting with AngularJS. By your requirement, I believe your best option is to create a service that retrieves the movie list and then use this service in both controllerA and controllerB.
module.factory('youtube', function() {
var movieListCache;
function getMovies(ignoreCache) {
if (ignoreCache || !movieListCache) {
movieListCache = $http...;
}
return movieListCache;
}
return {
get: getMovies
};
});
Then you just inject this service in both controllers.
module.controller('controllerA', ['youtube', function(youtube) {
youtube.get().then(function doSomethingAfterRetrievingTheMovies() {
});
}]);
module.controller('controllerB', ['youtube', function(youtube) {
youtube.get().then(function doAnotherThingAfterRetrievingTheMovies() {
});
}]);
If you need controllerA to manipulate the info before you use it in B then you could create more methods in the service. Something like this:
module.factory('youtube', function($q) {
var movieListCache,
deferred = $q.defer();
function getMovies(ignoreCache) {
if (ignoreCache || !movieListCache) {
movieListCache = $http...;
}
return movieListCache;
}
function getChangedMovies() {
return deferred.promise;
}
function setChangedMovies(movies) {
deferred.resolve(movies);
}
return {
get: getMovies,
getChanged: getChangedMovies,
setChanged: setChangedMovies
};
});
If you don't know what $q is, take a look at the docs. This is mandatory to handle async operations.
Anyway, there are some other ways of accomplishing this task too:
You could save the videos at $rootScope
If the controllers are father and son the you could use require to retrieve each other controller
IMHO, #1 is a generic solution; I'd use it only if there is no other option. And #2 is useful if you have an intrinsic need to communicate between these controllers, such as configuring or letting one know about the other's existence. There is a example here.
What you want to do is to share stateful singleton information; therefore, a service is the way to go.

Related

How to change Angular factory to resolve before injection

I have an existing application that uses a MapProvider like so:
mapModule.factory('MapProvider', ['$injector', function($injector) {
return $injector.get('GoogleMapsService');
}]);
This MapProvider is used extensively across the application and is injected into various other controllers and services (rightly or wrongly).
I now need to add a BaiduMapsService, which I have been able to get working as a test with:
mapModule.factory('MapProvider', ['$injector', function($injector) {
if(true) {
return $injector.get('GoogleMapsService');
} else {
return $injector.get('BaiduMapsService');
}
}]);
And flipping the if value accordingly. (Both of these services are using a TypeScript interface, so have the same methods). Now, I need to add a $http call to the API, which will return which map to use, based on the provided data. How can I make my factory asynchronous, without having to change all my MapProvider.someCallHere() calls to MapProvider.then(m => m.someCallHere()).
Ideally, when MapProvider is injected across my application, it will be able to resolve using the async data (only once), and then inject the necessary service afterwards.
Alternatively, is there a way to defer / delay loading Angular at all, until I make an API call and set some global data somewhere?
Thanks.
You can postpone the application bootstrap (also, don't use ng-app, do it manually) until you get data from server. I've answered this before on this question but each case has its own specific details.
I usually see a config value being declared on the app before the application gets bootstraped, this is very useful for multi-tenant apps. So that this preference values can be used in the whole app as an injected provider.
For example:
var app = angular.module('app', []);
// retrieve the $http provider
var ngInjector = angular.injector(["ng"]);
var $http = ngInjector.get("$http");
// load config function. Returns a promise.
function loadConfig(){
return $http.get("/config.json").then(function(response) {
// declare the configuration value on your app
app.constant("Config", response.data);
}, function(err) {
console.error("Error loading the application config.", err)
});
}
// Call loadConfig then bootstrap the app
loadConfig().then(function () {
angular.element(document).ready(function() {
angular.bootstrap(document, ["app"]);
});
});
Finally from your factory, you can use the Config constant to retrieve the preferred map.
mapModule.factory('MapProvider', ['$injector', 'Config', function($injector, Config) {
if(Config.preferedMap == 'GoogleMap') {
return $injector.get('GoogleMapsService');
} else {
return $injector.get('BaiduMapsService');
}
}]);
Only way I can think is to hold initialize whole angular (and modules) until you got your "config" (and set is as global variable).

Why move my $http calls into a service?

Currently I have calls like this all over my three controllers:
$scope.getCurrentUser = function () {
$http.post("/Account/CurrentUser", {}, postOptions)
.then(function(data) {
var result = angular.fromJson(data.data);
if (result != null) {
$scope.currentUser = result.id;
}
},
function(data) {
alert("Browser failed to get current user.");
});
};
I see lots of advice to encapsulate the $http calls into an HttpService, or some such, but that it is much better practice to return the promise than return the data. Yet if I return the promise, all but one line in my controller $http call changes, and all the logic of dealing with the response remains in my controllers, e.g:
$scope.getCurrentUser = function() {
RestService.post("/Account/CurrentUser", {}, postOptions)
.then(function(data) {
var result = angular.fromJson(data.data);
if (result != null) {
$scope.currentUser = result.id;
}
},
function(data) {
alert("Browser failed to get current user.");
});
};
I could create a RestService for each server side controller, but that would only end up calling a core service and passing the URL anyway.
There are a few reasons why it is good practice in non-trivial applications.
Using a single generic service and passing in the url and parameters doesn't add so much value as you noticed. Instead you would have one method for each type of fetch that you need to do.
Some benefits of using services:
Re-usability. In a simple app, there might be one data fetch for each controller. But that can soon change. For example, you might have a product list page with getProducts, and a detail page with getProductDetail. But then you want to add a sale page, a category page, or show related products on the detail page. These might all use the original getProducts (with appropriate parameters).
Testing. You want to be able to test the controller, in isolation from an external data source. Baking the data fetch in to the controller doesn't make that easy. With a service, you just mock the service and you can test the controller with stable, known data.
Maintainability. You may decide that with simple services, it's a similar amount of code to just put it all in the controller, even if you're reusing it. What happens if the back-end path changes? Now you need to update it everywhere it's used. What happens if some extra logic is needed to process the data, or you need to get some supplementary data with another call? With a service, you make the change in one place. With it baked in to controllers, you have more work to do.
Code clarity. You want your methods to do clear, specific things. The controller is responsible for the logic around a specific part of the application. Adding in the mechanics of fetching data confuses that. With a simple example the only extra logic you need is to decode the json. That's not bad if your back-end returns exactly the data your controllers need in exactly the right format, but that may not be the case. By splitting the code out, each method can do one thing well. Let the service get data and pass it on to the controller in exactly the right format, then let the controller do it's thing.
A controller carries out presentation logic (it acts as a viewmodel in Angular Model-View-Whatever pattern). Services do business logic (model). It is battle-proven separation of concerns and inherent part of OOP good practices.
Thin controllers and fat services guarantee that app units stay reusable, testable and maintainable.
There's no benefit in replacing $http with RestService if they are the same thing. The proper separation of business and presentation logic is expected to be something like this
$scope.getCurrentUser = function() {
return UserService.getCurrent()
.then(function(user) {
$scope.currentUser = user.id;
})
.catch(function(err) {
alert("Browser failed to get current user.");
throw err;
});
});
It takes care of result conditioning and returns a promise. getCurrentUser passes a promise, so it could be chained if needed (by other controller method or test).
It would make sense to have your service look like this:
app.factory('AccountService', function($http) {
return {
getCurrentUser: function(param1, param2) {
var postOptions = {}; // build the postOptions based on params here
return $http.post("/Account/CurrentUser", {}, postOptions)
.then(function(response) {
// do some common processing here
});
}
};
});
Then calling this method would look this way:
$scope.getCurrentUser = function() {
AccountService.getCurrentUser(param1, param2)
.then(function(currentUser){
// do your stuff here
});
};
Which looks much nicer and lets you avoid the repetition of the backend service url and postOptions variable construction in multiple controllers.
Simple. Write every function as a service so that you can reuse it. As this is an asynchronous call use angular promise to send the data back to controller by wrapping it up within a promise.

refactoring $rootScope.$apply in Angular

my MusicPlayer.js Angular service has a callback function wrapped in $rootScope.$apply that updates a specific object (musicPlayer.currentPlaybackTime) and is shared to all other controllers ( via applying to $rootScope).
I understand that you'll ideally want to limit any $rootScope pollution, so i'm looking at possible refactoring options that take away calling apply methods to $rootScope but allows my updated object to be shared across multiple controllers.
My research indicates that i'll need to register the other controllers (i.e. PlayerDashboardCtrl.js, PlaylistCtrl.js and AlbumListCtrl.js) that need my currentPlaybackTime object, but i'd like to understand what's the most efficient way of doing this.
Thank you.
var setSong = function(song) {
currentBuzzObject = new buzz.sound(song.audioUrl, {
formats: ['mp3'],
preload: true
});
currentBuzzObject.bind('timeupdate', function() {
$rootScope.$apply(function() {
musicPlayer.currentPlaybackTime = currentBuzzObject.getTime();
});
});
musicPlayer.currentSong = song;
};
The best way to share data between controllers is to make a service/factory and get data using these service from whichever controller you want. You will have to inject this service in all the controllers where you want to access them.
This egghead video will give you a clear understanding: Share data between controllers
Stackoverflow question similar to this: Stackoverflow answers to sharing data between controllers.
Live Demo: Fiddle to show data sharing.

Which things i can put in service in angular Js

I have read many articles but still could not find how to put stuff in services.
Currently this is my Service
angular
.module('users')
.factory('objectiveService', objectiveService);
objectiveService.$inject = ['$http', 'Restangular'];
function objectiveService($http, Restangular) {
return {
getObjectives: getObjectives,
getSingleObjective: getSingleObjective
};
function getObjectives(pid) {
var pr = Restangular
.all('api')
.all('users')
.one('subjects', pid)
.all('objectives');
return pr;
}
function getSingleObjective(oid) {
var pr = Restangular
.all('api')
.all('users')
.one('objectives', oid);
return pr
}
}
This is the controller:
var _vm = this;
this.objPromise = objectiveService.getObjectives(44);
function getData() {
var promise = _vm.objPromise;
promise
.getList(filters)
.then(function(result) {
$scope.gridData = result;
});
}
function remove(id) {
if (confirm('Are you sure you want to delete this!')) {
objectiveService.getSingleObjective(id).remove().then(function() {
$scope.getData();
});
}
}
// initial call
$scope.getData();
In this code i basically see no use to define service because I still has to use then() in the controller to assign data to Grid.
Also I can't use then() in service because there I don't have $scope to update the data.
People say to do all stuff in service but I am not able to figure out how.
Ideally I want to put all functions like remove(object_id) in service
IS it possible that I can just do objectiveService.remove(id) in controller.
But then I have to call $scope.getData() after deleting which I can't do in service
The reason to use services is not to avoid the use of .then. In your controller you would use .then like so:
objectiveService.getObjectives(filters)
.then(function(result) {
$scope.gridData = result;
});
.then is required as the call to get data occurs asynchronously.
Some reasons taken from John Papa's style guide:
The controller's responsibility is for the presentation and gathering of information for the view. It should not care how it gets the data, just that it knows who to ask for it.
This makes it easier to test (mock or real) the data calls when testing a controller that uses a data service.
Data service implementation may have very specific code to handle the data repository. This may include headers, how to talk to the data, or other services such as $http. Separating the logic into a data service encapsulates this logic in a single place hiding the implementation from the outside consumers (perhaps a controller), also making it easier to change the implementation.
If you put the code in the controller it also means it's not reusable. You can't use it in more than one controller or you can't you it in another service.

AngularJS. Best practice concerning proper two way data binding from a service

I have an 'Account' service which acts as a centralized data storage used in multiple controllers and views. This service will hold, besides getter and setter methods all data associated with two types of users, being a logged in user and an anomonous user.
The idea behind this service is that it should be used as a centralized data structure which will keep all associated views and controllers in synch. Eg: If a user logs in whe will know his email and all 'newsletter subscription' fields can be prefilled.
The current setup i use is as below. Note that each Async call on the server will return a promise.
// The Service
angular.module('A').provider('AccountService', [function() {
this.$get = function ($resource) {
var Account = {
getLoggedInAccountAsync : function () {
var Account = $resource(WebApi.Config.apiUrl + 'Account/Get');
return Account.get();
},
getUserData : function () {
return Account.userData;
},
setUserData : function (accountData) {
var merge = angular.extend((Account.currentAccountData || {}), accountData);
Account.currentAccountData = merge;
}
};
return Account;
}
});
// Our main app controller. Get's fired on every page load.
angular.module('A').controller('MainController', ['AccountService', function (AccountService) {
var loggedInAccount = AccountService.getLoggedInAccountAsync();
loggedInAccount.$then(loggedInAccountPromiseResolved);
function loggedInAccountPromiseResolved (response) {
if (response.data.isLoggedIn) {
AccountService.setAccountData(response.data);
}
};
return $scope.MainController= this;
}])
// Our specific controller. For example a newsletter subscription.
angular.module('A').controller('SpecificController', ['AccountService', function (AccountService) {
this.getUserData = AccountService.getUserData;
return $scope.Controller = this;
}])
// Newsletter subscription view
<input id="email" type="email" name="email" ng-model="SpecificController.getUserData().UserName"/>
Using the above code ensures that whenever we use the service to bind our data via Controller.getUserData().property to our view it will stay in synch throughout our entire app.
The code above will also throw if for example the .UserName value is not defined, or if there is no account data at all in case of an anomonous user. One way around this is to 'dump' our 'template' object within our service with null values this will ensure the key/values exist. Another way would be to use watchers and let our controller(s) 'write' to our service in case an user fills a field.
The first option gives me more flexability as i can centralize all the data binding in the service but it feels dirty because you never know what will happen with the server data, it could come in as a different format for example.
Does anyone have any other solution? I would prefer to not let my controllers do the writing of the data to the service.
Thank you for your time!
There are many questions here, I will answer as best as I can.
No, what you are doing is not a "best practice".
First, The model should be injected directly into the view, and maintaining the value is the responsibility of the Controller, with the help of "$scope". Your "ng-model="Controller.getUserData().UserName" is bad. There is a good example of what to do in the end of the blog article I noticed below.
Second, when you fetch data from a service, most of the time, the answer will be asynchronous, so you'd better take a look at the Promise API. The official doc of AngularJS is not always fantastic and sometimes the answer can be found on google groups or in blog article.
For your problem, here is a good article : http://markdalgleish.com/2013/06/using-promises-in-angularjs-views/
Firstly, if you use service in AngularJS, we expect a call to server or whatever that may not return data instantly. So we have two approaches of using ugly callback or beautiful $q.
I prefer using promise since it's cleaner to write. I will rewrite your snippets in a better way :
// Service
angular.module('A').provider('AccountService', [function() {
this.$get = function ($resource, $q) {
var Account = {
getUserData : function () {
var d = $q.defer();
d.resolve(Account.userData);
return d.promise;
}
};
return Account;
}
});
// Controller
angular.module('A').controller('Controller', ['AccountService', function (AccountService) {
var init = function() {
getUserData();
};
var getUserData = function() {
AccountService.getUserData().then(function(data) { $scope.username = data; });
};
init();
//return $scope.Controller = this; // you don't need to do this
}])
HTML:
<input id="email" type="email" name="email" ng-model="username"/>

Categories

Resources