pass id value between controllers angularjs - javascript

I'm trying to pass an id from one controller to another. I have a select menu that on selection will navigate you to the appropriate tournament. I would like to retrieve the tournament._id value in a different controller and then query that tournament for data. I'm new to angular and any help is appreciated. Thanks!
select menu
<select class="form-control" ng-model="vm.selectedTournamentId" ng-change="vm.showTournament()" >
<option value="">Select a tournament</option>
<option ng-repeat="tournament in vm.tournaments" value="{{ tournament._id }}">{{ tournament.name }}</option>
</select>
app.js
.controller('NavigationController', NavigationController);
NavigationController.$inject = ['TournamentService', '$q', '$location', '$scope', '$filter', '$state'];
function NavigationController(TournamentService, $q, $location, $scope, $filter, $state) {
var vm = this;
vm.tournaments = TournamentService.query();
vm.showTournament = function() {
var tournament = TournamentService.query({id: vm.selectedTournamentId}, function() {
vm.selectedTournament = tournament[0]
$state.go('dashboard.tournament')
});
}
}
dashboard.js
angular.module('Dashboard',[]).controller('DashboardController',
DashboardController).factory('TournamentService', TournamentService).factory('UserService', UserService).factory('TeamService', TeamService)
DashboardController.$inject = ['$scope','TournamentService','TeamService','UserService','$q'];
function DashboardController($scope, TournamentService, TeamService, UserService, $q) {
var vm = this;
var tournaments = TournamentService.query();
var users = UserService.query();
var teams = TeamService.query()
$q.all([tournaments, users, teams]).then(function(results) {
vm.users = users;
vm.availablePlayers = users;
vm.tournaments = tournaments;
vm.teams = teams;
})
}
TournamentService.$inject = ['$resource'];
function TournamentService($resource) {
return $resource('/api/tournaments/:id',{cache: true},{tournament: '#tournament'});
}
UserService.$inject = ['$resource'];
function UserService($resource) {
return $resource('/api/users/:id', {cache: true},{user: '#user'})
}
TeamService.$inject = ['$resource'];
function TeamService($resource) {
return $resource('/api/teams/:id',{cache: true}, {team: '#team'})
}
}());

Since you are using ui-router, I think what would be best for you to do here is to use $stateParams.
Instead of this:
vm.showTournament = function() {
var tournament = TournamentService.query({id: vm.selectedTournamentId}, function() {
vm.selectedTournament = tournament[0]
$state.go('dashboard.tournament')
});
}
Do this:
vm.showTournament = function() {
var tournament = TournamentService.query({id: vm.selectedTournamentId}, function() {
vm.selectedTournament = tournament[0];
$state.go('dashboard.tournament', {tournamentId: vm.selectedTournamentId});
});
}
The difference would be in the $state.go. Notice how I added an object with a property of tournamentId which equals the selected tournament id. This property will be passed to the next state you go to, which is dashboard.tournament.
Now in your second controller, you would also need to inject $stateParams and then access that tournament property by doing $stateParams.tournamentId. So you could set a variable to or like vm.tournament = $stateParams.tournamentId.
In order for this all to work, however, you would need to set some kind of param on the state that you are trying to send the tournament or tournament ID to.
Method 1:
$stateProvider
.state('dashboard.tournament', {
url: '/dashboard/tournament/:tournamentId'
templateUrl: //...,
controller: //...
});
The above has an :tournamentId spot in the URI which waits for the stateParams value to be set upon going to the state. So this would show something like /dashboard/tournament/7 if you did $state.go('dashboard.tournament', {id: 7});.
Method 2:
$stateProvider
.state('dashboard.tournament', {
url: '/dashboard/tournament'
templateUrl: //...,
controller: //...,
params: {
tournamentId: null
}
});
Noticed how we removed :tournamentId from the url value.
You would set the stateParams the same way using something like $state.go('dashboard.tournament', {tournamentId: 7});, however now nothing will be added to the URI.
In both method 1 and method 2, you can access the tournamentId value in your second controller via $stateParams.tournamentId.
Which method should you use?
The only difference really is that method 2 will hide the param value from the URI. This is especially useful in abstract states, for example, where there should be no URI visible at all. Otherwise, they're basically the same -- just minor differences and a different way of achieving the same thing.
If you want your URL to look like http://domain.com/dashboard/tournament/7, then use method 1.
If you want your URL to look like http://domain.com/dashboard/tournament, then use method 2.
Refer to the routing docs for more info.

One way of achieving this will be passing the tournament id to the dashboard controller as a state parameter, so in this way when you select the tournament from the menu you will be redirected to the dashboard of that specific tournament.
Add the parameter to your state url on $stateProvider:
.state('app.dashboard', {
url: '/dashboard/:tournamentId',
On your app.js (Menu Controller):
$state.go('dashboard.tournament',{'tournamentId': vm.selectedTournamentId});
and access it on your DashboardController using $stateParams (don't forget to inject $stateParams to your controller):
var tournamentId = $stateParams.tournamentId;

Related

AngularJS Proper way to pass variables

I would like to make them global so I can use [color] and [shape] throughout the whole script. I will need each one to update independently but as I continue to add to the site I am going to need to use both together.
Live preview
Example does not work: $scope.shapeSelected = response.data[color][shape];
Example does work: $scope.shapeSelected = response.data.blue[shape];
var app = angular.module("computer", ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/main', {
controller: 'MainCtrl'
}).
otherwise({
redirectTo: '/main'
})
}])
.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {
$scope.colorType = function(color) {
$http.get('stuff.json').then(function(response) {
$scope.colorSelected = response.data.type[color];
});
}
$scope.shapeType = function(shape) {
$http.get('shapes.json').then(function(response) {
$scope.shapeSelected = response.data[color][shape]; // <--- [color] is not getting pulled in on this function.
var resultsColorShape = $scope.shapeSelected; // <--- I would like to be able to store this incase i need it later.
console.log('resultsColorShape');
});
}
}]);
You don't have to pass argument to your functions. if you defined ng-model="Color" you can use $scope.Color in your javascript code:
change in html:
ng-change="colorType()"
ng-change="shapeType()"
and js to:
$scope.colorType = function() {
$http.get('stuff.json').then(function(response) {
$scope.colorSelected = response.data.type[$scope.Color];
});
}
$scope.shapeType = function() {
$http.get('shapes.json').then(function(response) {
$scope.shapeSelected = response.data[$scope.Color][$scope.Shape];
});
}
If your question is about passing the variables or sharing the data properly across functions then this should help you.
In your scenario. As the ng-change functions are assigned.
When the ng-change function is triggered if you don't have a ng-model try to save the new value that is the passed parameter in the $scope so as to access it across all the other functions in that controller.
If you have a ng-model declared for your element then just use the attribute for the ng-model as the reference variable . e.g: ng-model="xyz" then $scope.xyz would give you the desired value of the element.
This is how you can access the element value accordingly

AngularJS service object is not being updated across views/controllers

I have a factory, "itemData", that holds a service.
app.factory('itemData', function () {
var itemData = {
Title: 'I should be different',
getTitle: function () {
return itemData.Title;
},
setTitle: function (title) {
return itemData.Title=title;
},
// This is the function to call all of the sets for the larger object
editItem: function (entry)
{
itemData.setTitle(entry);
}
};
return itemData;
});
I have 2 controllers (in different files) associated with 2 separate views.
The first:
// IndexCtrl
app.controller("IndexCtrl", ['$scope','$window','itemData',
function($scope, $window, itemData) {
var entry = "I'm different";
// After a submit is clicked
$scope.bttnClicked = function (entry) {
itemData.editItem(entry);
console.log(itemData.getTitle(); //<--itemData.Title has changed
// moves to page with other controller
$window.location.href = "edit.html";
};
}
]);
and the second, which is not doing what I want:
app.controller("editItemCtrl", ['$scope', '$window', 'itemData',
function ($scope, $window, itemData){
$scope.item = {
"Title": itemData.getTitle(), //<--- Title is "I should be different"
}
}]);
Do you have some kind of router in place in your Angular app? When you change the location href, is it actually causing full page reload?
Services are held in memory and therefore will not maintain state across page reloads.
I consider that the expression ['$scope', '$window', 'itemData',
function ($scope, $window, itemData) force to initialize the dependency injection and for this reason you had two different object.
if you see the doc https://docs.angularjs.org/guide/controller there is a section called Setting up the initial state of a $scope object in this section was described the case of scope but I consider that may be extended at the list of the service in the [...] even in the angular.module(moduleName,[...]) if the [....] are filled the functin return a new module and only for empty square bracket return the current module instance
I hop that this can help you

How to react to change in data in a service in angularjs on a controller

I want to be able to share data between two controllers so that I can send a boolean to the service from the first controller which is turn triggers a change in the second controller.
Here is what the service looks like
exports.service = function(){
// sets Accordion variable to false ;
var property = true;
return {
getProperty: function () {
return property;
},
setProperty: function(value) {
property = value;
}
};
};
Now the first controller
exports.controller = function($scope, CarDetailsService, AccordionService ) {
$scope.saveDetails = function() {
AccordionService.setProperty(false);
}
}
and the second one
exports.controller = function($scope, AccordionService ) {
$scope.isCollapsed = AccordionService.getProperty();
}
The use case is that when i click on a button on the first controller,the service updates the data inside it, which is then served on the second controller, thus triggering a change in the second controller.
I have been looking around for quite some time but couldn't find a solution to this. Maybe im just stupid.
On the second controller you can $watch the variable you change in the first:
scope.$watch('variable', function(newValue, oldValue) {
//React to the change
});
Alternatively, you can use the $broadcast on the rootScope:
On the first controller:
$rootScope.$broadcast("NEW_EVENT", data);
On the other controller:
scope.$on("NEW_EVENT", function(event, data){
//use the data
});

Not able to get the content of model in multiple controllers AngularJS

Hope, my question itself, conveys what I am look for.
Will put the words in detail
1. Created the Module.
var ang = angular.module('myApp', []);
I have a controller called controller1, and includes the 'campaign' factory.
//controllerone.js
ang.controller('controller1', function(campaign){
$scope.campaigns = new campaign();
//Here the whole campaign object is displayed with data, refer the Image 1 attached
console.log($scope.campaigns);
});
ang.factory('campaign', function($http){
var campaign = function(){
this.timePeriodList = buildTimePeriodList();
...
...
this.campaignList = [];
};
Campaigns.prototype.fetchCampaigns = function() {
//Some service call to load the data in this.campaignList
};
});
Now trying to call the same campaign factory in the second controller, getting only the object structure, not getting the data.
//controlertwo.js
ang.controller('controller2', function(campaign){
$scope.campaigns = new campaign();
//Here only the campaign object structure is displayed, but no data for campaignList, ref image 2 attached
console.log($scope.campaigns);
});
Since, factory service is a singleton object, I was expecting for same result as I got in controllerone.js,
Image 1:
Image 2:
In angular factory I would suggest a different approach.Try not to attach anything to the Prototype of a object. Instead you can create an object in the scope of your angular factory, attach what you want to it and return it. For example:
ang.factory('campaign', function ($http) {
var campaign = {};
campaign.method1 = function () {
//..
}
campaign.campaignList = [];
//...
campaign.fetchCampaigns = function () {
//Some service call to load the data in this.campaignList
};
});
//Than in your controllers if campaign is injected you can use it that way:
ang.controller('controller2', function (campaign) {
campaign.fetchCampaigns();// This will fill the list and it will remain filled when other controllers use this factory...
console.log(compaign.campaignList);
});
Anything you dont want to be exposed out of the factory simply do not attach it to the campaign object.
Create campaign in a service. Eg-campaignService
Updated code---
var ang = angular.module('myApp', []);
ang.service('campaignService', function($scope){
var campaign = function(){
this.timePeriodList = buildTimePeriodList();
...
...
this.campaignList = [];
}
return campaign;
});
ang.controller("controller1", ["campaignService",
function($scope, $rootScope, campaignService){
$scope.campaigns=campaignService.campaign();
}
]);
ang.controller("controller2", ["campaignService",
function($scope, $rootScope, campaignService){
$scope.campaigns=campaignService.campaign();
console.log($scope.campaigns);
}
]);

Maintain model of scope when changing between views in AngularJS

I am learning AngularJS. Let's say I have /view1 using My1Ctrl, and /view2 using My2Ctrl; that can be navigated to using tabs where each view has its own simple, but different form.
How would I make sure that the values entered in the form of view1 are not reset, when a user leaves and then returns to view1 ?
What I mean is, how can the second visit to view1 keep the exact same state of the model as I left it ?
I took a bit of time to work out what is the best way of doing this. I also wanted to keep the state, when the user leaves the page and then presses the back button, to get back to the old page; and not just put all my data into the rootscope.
The final result is to have a service for each controller. In the controller, you just have functions and variables that you dont care about, if they are cleared.
The service for the controller is injected by dependency injection. As services are singletons, their data is not destroyed like the data in the controller.
In the service, I have a model. the model ONLY has data - no functions -. That way it can be converted back and forth from JSON to persist it. I used the html5 localstorage for persistence.
Lastly i used window.onbeforeunload and $rootScope.$broadcast('saveState'); to let all the services know that they should save their state, and $rootScope.$broadcast('restoreState') to let them know to restore their state ( used for when the user leaves the page and presses the back button to return to the page respectively).
Example service called userService for my userController :
app.factory('userService', ['$rootScope', function ($rootScope) {
var service = {
model: {
name: '',
email: ''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
}]);
userController example
function userCtrl($scope, userService) {
$scope.user = userService;
}
The view then uses binding like this
<h1>{{user.model.name}}</h1>
And in the app module, within the run function i handle the broadcasting of the saveState and restoreState
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
As i mentioned this took a while to come to this point. It is a very clean way of doing it, but it is a fair bit of engineering to do something that i would suspect is a very common issue when developing in Angular.
I would love to see easier, but as clean ways to handle keeping state across controllers, including when the user leaves and returns to the page.
A bit late for an answer but just updated fiddle with some best practice
jsfiddle
var myApp = angular.module('myApp',[]);
myApp.factory('UserService', function() {
var userService = {};
userService.name = "HI Atul";
userService.ChangeName = function (value) {
userService.name = value;
};
return userService;
});
function MyCtrl($scope, UserService) {
$scope.name = UserService.name;
$scope.updatedname="";
$scope.changeName=function(data){
$scope.updateServiceName(data);
}
$scope.updateServiceName = function(name){
UserService.ChangeName(name);
$scope.name = UserService.name;
}
}
$rootScope is a big global variable, which is fine for one-off things, or small apps.
Use a service if you want to encapsulate your model and/or behavior (and possibly reuse it elsewhere). In addition to the google group post the OP mentioned, see also https://groups.google.com/d/topic/angular/eegk_lB6kVs/discussion.
Angular doesn't really provide what you are looking for out of the box. What i would do to accomplish what you're after is use the following add ons
UI Router & UI Router Extras
These two will provide you with state based routing and sticky states, you can tab between states and all information will be saved as the scope "stays alive" so to speak.
Check the documentation on both as it's pretty straight forward, ui router extras also has a good demonstration of how sticky states works.
I had the same problem, This is what I did:
I have a SPA with multiple views in the same page (without ajax), so this is the code of the module:
var app = angular.module('otisApp', ['chieffancypants.loadingBar', 'ngRoute']);
app.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/:page', {
templateUrl: function(page){return page.page + '.html';},
controller:'otisCtrl'
})
.otherwise({redirectTo:'/otis'});
}]);
I have only one controller for all views, but, the problem is the same as the question, the controller always refresh data, in order to avoid this behavior I did what people suggest above and I created a service for that purpose, then pass it to the controller as follows:
app.factory('otisService', function($http){
var service = {
answers:[],
...
}
return service;
});
app.controller('otisCtrl', ['$scope', '$window', 'otisService', '$routeParams',
function($scope, $window, otisService, $routeParams){
$scope.message = "Hello from page: " + $routeParams.page;
$scope.update = function(answer){
otisService.answers.push(answers);
};
...
}]);
Now I can call the update function from any of my views, pass values and update my model, I haven't no needed to use html5 apis for persistence data (this is in my case, maybe in other cases would be necessary to use html5 apis like localstorage and other stuff).
An alternative to services is to use the value store.
In the base of my app I added this
var agentApp = angular.module('rbAgent', ['ui.router', 'rbApp.tryGoal', 'rbApp.tryGoal.service', 'ui.bootstrap']);
agentApp.value('agentMemory',
{
contextId: '',
sessionId: ''
}
);
...
And then in my controller I just reference the value store. I don't think it holds thing if the user closes the browser.
angular.module('rbAgent')
.controller('AgentGoalListController', ['agentMemory', '$scope', '$rootScope', 'config', '$state', function(agentMemory, $scope, $rootScope, config, $state){
$scope.config = config;
$scope.contextId = agentMemory.contextId;
...
Solution that will work for multiple scopes and multiple variables within those scopes
This service was based off of Anton's answer, but is more extensible and will work across multiple scopes and allows the selection of multiple scope variables in the same scope. It uses the route path to index each scope, and then the scope variable names to index one level deeper.
Create service with this code:
angular.module('restoreScope', []).factory('restoreScope', ['$rootScope', '$route', function ($rootScope, $route) {
var getOrRegisterScopeVariable = function (scope, name, defaultValue, storedScope) {
if (storedScope[name] == null) {
storedScope[name] = defaultValue;
}
scope[name] = storedScope[name];
}
var service = {
GetOrRegisterScopeVariables: function (names, defaultValues) {
var scope = $route.current.locals.$scope;
var storedBaseScope = angular.fromJson(sessionStorage.restoreScope);
if (storedBaseScope == null) {
storedBaseScope = {};
}
// stored scope is indexed by route name
var storedScope = storedBaseScope[$route.current.$$route.originalPath];
if (storedScope == null) {
storedScope = {};
}
if (typeof names === "string") {
getOrRegisterScopeVariable(scope, names, defaultValues, storedScope);
} else if (Array.isArray(names)) {
angular.forEach(names, function (name, i) {
getOrRegisterScopeVariable(scope, name, defaultValues[i], storedScope);
});
} else {
console.error("First argument to GetOrRegisterScopeVariables is not a string or array");
}
// save stored scope back off
storedBaseScope[$route.current.$$route.originalPath] = storedScope;
sessionStorage.restoreScope = angular.toJson(storedBaseScope);
},
SaveState: function () {
// get current scope
var scope = $route.current.locals.$scope;
var storedBaseScope = angular.fromJson(sessionStorage.restoreScope);
// save off scope based on registered indexes
angular.forEach(storedBaseScope[$route.current.$$route.originalPath], function (item, i) {
storedBaseScope[$route.current.$$route.originalPath][i] = scope[i];
});
sessionStorage.restoreScope = angular.toJson(storedBaseScope);
}
}
$rootScope.$on("savestate", service.SaveState);
return service;
}]);
Add this code to your run function in your app module:
$rootScope.$on('$locationChangeStart', function (event, next, current) {
$rootScope.$broadcast('savestate');
});
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
Inject the restoreScope service into your controller (example below):
function My1Ctrl($scope, restoreScope) {
restoreScope.GetOrRegisterScopeVariables([
// scope variable name(s)
'user',
'anotherUser'
],[
// default value(s)
{ name: 'user name', email: 'user#website.com' },
{ name: 'another user name', email: 'anotherUser#website.com' }
]);
}
The above example will initialize $scope.user to the stored value, otherwise will default to the provided value and save that off. If the page is closed, refreshed, or the route is changed, the current values of all registered scope variables will be saved off, and will be restored the next time the route/page is visited.
You can use $locationChangeStart event to store the previous value in $rootScope or in a service. When you come back, just initialize all previously stored values. Here is a quick demo using $rootScope.
var app = angular.module("myApp", ["ngRoute"]);
app.controller("tab1Ctrl", function($scope, $rootScope) {
if ($rootScope.savedScopes) {
for (key in $rootScope.savedScopes) {
$scope[key] = $rootScope.savedScopes[key];
}
}
$scope.$on('$locationChangeStart', function(event, next, current) {
$rootScope.savedScopes = {
name: $scope.name,
age: $scope.age
};
});
});
app.controller("tab2Ctrl", function($scope) {
$scope.language = "English";
});
app.config(function($routeProvider) {
$routeProvider
.when("/", {
template: "<h2>Tab1 content</h2>Name: <input ng-model='name'/><br/><br/>Age: <input type='number' ng-model='age' /><h4 style='color: red'>Fill the details and click on Tab2</h4>",
controller: "tab1Ctrl"
})
.when("/tab2", {
template: "<h2>Tab2 content</h2> My language: {{language}}<h4 style='color: red'>Now go back to Tab1</h4>",
controller: "tab2Ctrl"
});
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
<body ng-app="myApp">
Tab1
Tab2
<div ng-view></div>
</body>
</html>

Categories