Pass service result to other controller - angularjs

I am calling getLanguageSpecificData(LangCode) service from home controller and saving the data into localStorage. On Home page there are Language links, if user click on English then it will redirect to a second template. But the problem is that still home controller getLanguageSpecificData(LangCode) service is not completed its execution.So in second Controller when I am trying to get result from localStorage it is incorrect(not updated).
So can you please tell which is better approach in this situation ?
HomeController code :
app.controller('homeController',function($scope,$localStorage,$appService){
$scope.loadlanguagefile = function(langcode){
$troubleshootingService.getLanguageSpecificData(LangCode).then(function(responce){
$localStorage.data = responce.data;
});
}
});
'loadlanguagefile' function is called when user click on Enlgish link and app is redirect to second template. here is secondController code :
app.controller('secondController',function($scope,$localStorage){
$scope.data = $localStorage.data;
});

As per my suggestion, you should use callback function to do your need full, when the function is called make the English click disable , and if your result is successful the make that enable. It will be something like this:
getLanguageSpecificData(LangCode,callback:(dataToReturn:any)=>void):any{
//logic here to get data to return
callback(dataToReturn);
}
For calling this method -
1- before calling the method make English click disable.
2- then call the method-
getLanguageSpecificData(imputLangCode,(result)=>{
//logic for data modification
//logic to enable English click
});
3- Enable the English click inside the call of the method.

Related

making a ui-sref functionality in a .js

Setting:
I have an angular app.
What I have:
I have this: ui-sref="providerDetail({id:provider.id})" functioning.
It is a functioning link to a page giving details on a given provider.
What I want:
I have a button that submits a form and makes a new provider. This works. But I also want this button to forward the user to that new provider's detail page.
I have a function running that prints the id of the new provider to the console when it is made, I just can't figure out how to forward the user to the appropirate location.
Note:
I can add this to the function:
window.location = "/dashboard.html#!/providerDetail/" +id;
And it will take me to the new page, but I get this impression that this is a bad route to take.
Don't manually change the URL in AngularJS application, do it in Angular way so that you don't need to worry about manually kick of digest cycle. From function you could call $state.go method to navigate between states.
function myFunction(id) {
$state.go('providerDetail', { id: id})
}
Note: Please make sure you inject $state inside you controller.

communicating between two controller in angularjs using factory

I have created a plunker that communicates between two different controller in nested views using factory. Below is the url of plunker.
https://plnkr.co/edit/fWA2Xugjbkf3QvHKfTa0?p=preview .
Here is the factory.
routerApp.factory("widgetService",function($state){
var callbackFunctions=[];
var counter=0;
var addWidget=function(name){
callbackFunctions[0](name);
}
var addCallback=function(callback){
if (callbackFunctions.length===0) {
callbackFunctions.push(callback);
}
}
return{
addCallback: addCallback,
addWidget: addWidget
}
})
Scenario 1:
1. Click on "List" menu under the home page.
2. Click on "verify" button. notice the change in highlighted area with yellow. Text changes from "Chandan" to "singh1".
3. Click again on verify button. Text changes from "singh1" to "singh2". So i am able to communicate between two controller in this.
Scenario 2:
1. Repeat the scenario 1 till step 2.
2. Click on "PARAGRAPH" menu under home page.
3. Click on "List" menu under home page. Click verify button. The text wont change. It will remain "chandan".
Communication is not working as we change the state.
Also i have observed that the model is changing but same is not getting reflected in view. Moreover if we bind the view to rootscope, view is getting updated.
Please clarify.
When you switch between list and paragraph states, your list controller is destroyed (and recreated next time you go to list). So when it is recreated it gets a new scope.
The callbackFunction that is registered in your service, refers to the changeMyName() function on the old controller scope, so whenever you call addWidget() in your service, you're actually calling the callback in your old scope.
To make this work as expected (at least in your sample code here), you would have to change your service to allow changing the old callback in the addCallback()-function. Something like this:
var addCallback=function(callback){
callbackFunctions[0] = callback;
}

Run a function only the first time when AngularJS gets loaded

I'm using angular-seed template (AngularJS) and I have routeProvider setup and such, now I want to execute a function (which resides in a factory), but only the very first time when the page gets loaded. I found many solutions for this, but I don't want to execute the code each time the users switches between tabs (via routeProvider of course, page doesn't get reloaded) - the code must be executed only when the whole page gets (re)loaded.
How should I approach this? I tried to call the function from run and then broadcast the event when page gets loaded, but there are no event listeners - I guess that is because the run part gets executed before the controllers are setup, so there are no listeners attached at the time when the event gets broadcast.
So, any suggestions how to approach this?
UPDATE
Use case:
when user types the url in the page, the page gets loaded
when pages gets loaded, a $http.get request is performed, which gets a random content
this content can be changed only by clicking a button, to explicitly request a change of content.
if users clicks to a different page e.g. view2 (routeProvider) and then back to the view1, the content must not change
when users refreshes the page (F5), the content changes again (or as already stated, by a click of a button)
Use the run method:
app.run(function(yourService){
yourService.cacheRandomContent();
});
It runs only once after the app is bootstrapped and services are created.
To access the data in controller, just inject the same service:
app.controller('someCtrl',function($scope, yourService){
yourService.getCachedRandomContent().then(function(resp){
$scope.data = resp.data;
});
});
Your service would be something like:
app.service('yourService',function($http){
var promise;
return {
cacheRandomContent: function(){
promise = $http.get();
},
getCachedRandomContent : function(){
return promise;
}
}
});

Get the url that a user is coming from AngularJS

If an user is coming from an specific page i need to do get some values out of a cookie and change what the users sees.
Now, the issue is that i cannot find a way to view what page the user is coming from.
EDIT: This is intended to capture when the users clicks back in a page and save the state of the previous page.
Any ideas?
Thanks in advance
Solved. Every time i load a page i'm saving the url, so when i get to this page i just have to read it to tell. Thanks!
You can use browser history in our javascript or you can write your last page in cookies and get the last link then update it
Using cookies will indeed fix this for you. So when a user goes to a new page - set a cookie like:
app.controller('myController',['$scope', '$location', $cookies], function($scope, $location, $cookies){
if($cookies.get('page') == '/index'){
//do stuff if user came from index
}
$scope.pageChanged = function(value){
$cookies.put('page', value);
$location.path('/index');
}
}
just make sure you use the pageChanged function to set your page every time user changes pages.
Using the $routeProvider you can use the resolve function to detect when a new route has been loaded.
Another way would be to listen for the event $routeChangeSuccessor $routeChangeError and get the information needed from the service $location or $route.
If you want a sample just ask me, I'll try to post one as soon as I have free time.

Why $http in ng-init is not getting called everytime the view is loaded - AngularJS

I have modified my question as per my observation.$http request on server side is not happening whenever the view is called second or third or so on times although initWishList (ng-init) is getting called. The scenario is as below:
I have a My Account tab in the nav-bar, which opens a view having options like MyWishlist, My Address etc. When My wishlist is clicked for the first time, $http request happens, but when I again click on My Account (this time I don't see any call on server side when the .html view is loaded) , and then if I click My Wishlist , the controller is called but $http isn't called (this time I again dont see any call on server side from $http) but I can see the alert Init Called
Why so?
$scope.initWishList = function(){
alert('Init called')
$http.get("/get_wish_list/")
.success(function (response) {
$scope.refreshWishList(JSON.parse(response["products_json"]));
})
.error(function(){
console.log('Error');
});
};
Hope I have explained the scenario properly.
Controllers gets intialized only once when angular parses ng-controller directive. Since controller is initialized once, ng-init will also run once.
For your satisfaction, add a break point in the your controller on the first line, see when you hit that break point. Are you hitting that break point, every time you click the tab ? If not, ng-init will not be called every time

Resources