I have a page where one controller shows all of the logged in user's teams, and another controller allows the user to update a team. When the user updates the team name, I want the controller that displays all the teams to notice that a team has been updated and update it's variable accordingly.
I've been googling around and it seems there's lots of questions and lots of different ways to do this. Ideally i'd like to be able to just update a factory variable and all the controllers would notice that the value has been updated. Not sure if that is how angular works though.
Example:
var myapp= angular.module('myapp', []);
...
// This gets the teams that a user is associated with
myezteam.factory('teams', function($http) {
// Get the teams associated with the logged in user
return {
getTeams: function(callback) {
$http.get(baseUrl+'v1/teams/all' + apiKey)
.success(function(response) {
callback(response);
});
}
}
});
Controller which gets all the teams
// This controller is used to set the user profile links
myapp.controller('TemplateProfileController', ['$scope', '$http'', 'teams', function($scope, $http, teams) {
// Gets all of a user's teams from the "teams" factory
getTeams = function() {
teams.getTeams(function(response) {
$scope.teams = response;
});
}
$scope.teams = getTeams(); // Call on page load
}]);
Controller which handles the editing of a team
// Controller for editing a team
myapp.controller('EditTeamController', ['$scope', '$http', '$routeParams', 'teams', function($scope, $http, $routeParams, teams) {
// Get the team that we're editing
getTeam = function() {
$http.get(baseUrl+'v1/teams/' + $routeParams.id + apiKey)
.success(function(response) {
$scope.team = response;
});
}
// Update the team and refresh the list of all teams
$scope.updateTeam = function() {
$http.post(baseUrl+'v1/teams' + apiKey, $scope.team)
.success(function(response) {
// NEED TO SOMEONE TRIGGER THE TempalteProfileController to get the teams from the factory again
})
}
getTeam(); // Call on page load;
}]);