Where to store the current state data using angular js? - angularjs

This issue is happening here.
Plunker link -> https://run.plnkr.co/NMW85SbYq76ujSjV/
I need to store the current state data somewhere apart from local storage using angular js. I have a list of models(cards) in one angular page. And there are two tabs in each card. First tab is having only simple text but second tab is having one button. So when a user clicks on the button (which is present in the second tab) then it redirects to new state where we are showing the description of the current model.
Here one problem is there. When user is on first state (where all of the models are visible) then this user is free to select any tab from any model. So suppose, we have 10 models and user select tab 2 for model 2, 4, 5, and 9. So here the view is like model 1, 3, 6, 7, 8 and 10 will be showing the tab 1 content and rest of the models will be showing the tab 2 content. Now when he/she clicks on the button present in second tab(of any model) then it redirects to description of model state. And here is button to go back to previous state. When he/she clicks on this button then it redirects to models state but the it's showing tab 1 content in all of the models instead of previous selected tabs accordingly.
So how can i handle this situation. I want to show previous state when a user comes back fro description state to models state.
Please help me guys. Please click on the above link to get the implemented plunker sample. Any lead would be appreciated.
Thanks :)

You have to create a service and move the "flag" variable to the JSON.
I have modified your plunker. Please check.
https://plnkr.co/edit/5k8hXbCIid4NonSL4Y9k?p=preview
var getData = {};
getData.get = $http.get('template.json')
.then(function(response) {
console.log(response);
return response.data;
})
return getData;
});
myRouterApp.component('myModels', {
templateUrl: 'models.html',
controller: ['$scope', '$http', '$state','getModelSvc', function TrialCtrl($scope, $http, $state,getModelSvc) {
$scope.models = [];
console.log(getModelSvc);
getModelSvc.get.then(function(data) {
$scope.models = data.models;
console.log($scope.models);
})

Related

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;
}

clear text input on another controller

is it possible to clear all fields in one controller by clicking on a button from the previous controller?
I'm trying to do so by setting cache: false in routes.js in the controller that needs to be cleared, however, I realized that it clears the controller's fields every time it's loaded.
I need to be able to clear the fields of the pages once a user clicks on login, however, I also need to be able to go back to the previous pages once I enter the "review info" page.
How should I go about this?
If you are using ionic version-1 framework, then use
$scope.logout = function(){
// first, clear the history
$ionicHistory.clearHistory();
// clear the cache before you navigate to a page
$ionicHistory.clearCache().then(function(){
$state.go("app.login");
});
}

Angularjs: Restore active tab on screen-1 when navigating back from screen-2

I have a screen-1 ('home' screen) which has three tabs (say tab1, tab2, and tab3). When app launches, the 'tab3' is active (in homeController.js I have set "$scope.active='tab3'").
Now when I open 'tab1' (so 'active' class updated to 'tab1') and redirects from this 'tab1' to another screen-2 ($location.path('/pathToScreen2') using routing), the screen-2 launches which has a back button, onclick of back button ($location.path('/pathToScreen1')), it navigates back to screen-1.
Now when screen-1 is launched, the active tab is 'tab3' rather I want 'tab1' should be active (probably every time when homeController gets loaded, It would initialise "$scope.active='tab3'"). How can I accomplish this?
With the help of Mikki, below is how I achieved this.
ActiveTabService:
angular.module("DemoApp")
.service('ActiveTabService', function(){
var activeTab = 'tab3';
return {
getActiveTab: function(){
return activeTab;
},
setActiveTab: function(tab){
activeTab = tab;
}
}
});
Here is the complete demo with routing and multiple screens.
You should not save states inside controllers variables, because controller has it's own lifecycle of destroying with all it's defined variables.
So what you need here - is create some kind of state service and initialize there your active tab. Inject this service across all controllers related to tab functionality, and set to this state service active tab once user entered to some controller.
P.S. Services are singletons, so if you inject service to few controllers they will all have links to the same object and it will not be destroyed before you will do it manually

Retain Tab number in Navigation AngularJs

So I am relatively new to AngularJs and I am trying to figure out the best way for a tabController to remember what tab was previously clicked when switching to a new controller. So the situation would be I have 3 tabs. I click on tab 3 and then I click on something inside of it bringing me to a new controller and HTML template... What is the best way if I hit a "back" Button I created in that controller to remember exactly the state of it being the 3 tab.
I tried using $rootScope and then in each controller setting the tab number and setting the tabcontroller = $rootScope... but that was chaotic and too repetitive, and its not the right way.
This is not about $windoe.back(), this refers to coming up with a way that no matter where the navigation is the tab number is retained.
You can use a factory for this. In angular, a factory is a singleton, meaning only one instance of it exists for the whole project. Thus, by making something with it in one controller (and saving what you've did), you can access your changes in another controller.
angular.module('awesomeApp')
.factory('tabHistoryFactory', function () {
var tabHistory = {
setPrevTab: function(tab) { tabHistory.prevTab = tab; },
getPrevTab: function() { return tabHistory.prevTab; }
};
return tabHistory;
});
Then, in your first controller you'll have to inject this factory and before changing to another tab, just save the tab you're on using tabHistoryFactory.setPrevTab(tab). Then, in your second controller, you can access your previous tab by using tabHistoryFactory.getPrevTab(). Similarly, you can customize the behavior of your tab history by implementing other functions alongside those two.
Good luck!

Can I keep the model value when click browser back button with angularjs?

I am new to AngularJS, I have a dropdown and a link. When I click the link, Anagularjs will route a different view (for example, display a chart and table).
Then when I click browser's back button, the dropdown will show the default value, other than the value I selected before.
Is it possible to let AngularJS remember the selected value of my dropdown when the link is clicked when I click browser's back button?
<select ng-model="selectedManagerFilter" ng-init="selectedManagerFilter= selectedManagerFilter || '*'"
ng-options="item.Code as item.Name for item in ManagerFilters" id="lstManagementGroup" name="lstManagementGroup"></select>
Your scope will get cleared when you exit the page and recreated with the default values when you get back to it.
You have 2 options:
use a Service to keep this kind of information (like selectedItem from your dropdown) and other useful things. The option selected in the dropdown should be bound to the service object:
angular.module('shared').factory('UsefulService', function() {
var UsefulService = {};
UsefulService.myPageSettings = {
currentDropDownItem: 1, //this is what you need
otherSetting: "blah"
};
return UsefulService;
});
and in your controller you should bind the scope variable to it (don't forget to require the UsefulService in your controller's dependencies):
$scope.myDearSettings = UsefulService.myPageSettings;
and then access it with $scope.myDearSettings.currentDropDownItem;
you can set a hash on your route when the dropdown changes (bound to the value) so when you hit Back you will get to the same state because of the hash. Basically, the url in your address bar will look like: http://your_server:your_port/myPage#Today where Today is the selected item.
The most recommended solution is option #1.

Resources