Shayan Khan Shayan Khan - 1 year ago 59
AngularJS Question

How to get param from one controller to another?

My question is best explained when I straight go to the code.

HTML part:

<div class="panel panel-default post" ng-repeat="post in posts">
<div class="panel-body">
<div class="row">
<div class="col-sm-2">
<a class="post-avatar thumbnail" href="/profile#/{[ post.profileID ]}">
<div class="text-center">{[ user.fullname ]}</div>

When I click on the /profile#/{[ post.profileID ]} link - it takes me to the profile page. All good here.

However, I am using ngView so I have separated it like this:

<div class="col-md-3">
<div>Some HTML stuff</div>

<div class="col-md-6">
<div ng-view></div>

<div class="col-md-3">
<div>Some HTML stuff</div>

My ngView makes use of the /profile#/{[ post.profileID ]} param and I use it to display whatever I have to display.

The problem:

I can get the profileID param in my angular controller but once I get it, how will I be able to pass it onto other controllers?

My controller looks like the below:

var profileApp = angular.module('profileApp', ['ngRoute']);

profileApp.config(function($routeProvider) {

.when('/:id', {
templateUrl : 'partial/profile/feed.html',
controller : 'mainController'

.when('/posts:id', {
templateUrl : 'partial/profile/posts.html',
controller : 'postsController'


profileApp.controller('mainController', ['$scope', '$http', '$routeParams', function($scope, $routeParams){



profileApp.controller('postsController', ['$scope', '$routeParams', function($scope, $routeParams){



As you can see, I get get the param passed from the HTML link and use it in the mainController but how will I get the param to be a link in the col-md-3 (just like the original /profile#/{[ post.profileID ]})?

Hope this makes sense. It's has been driving me nuts!


Answer Source

So I did some research into this and I just ended up using services.

See below for the answer:

profileApp.service('globalParams', function() {
var profileID = '';

return {
    getProfileID: function() {
        return profileID;
    setProfileID: function(value) {
        profileID = value;

You then pass the service into the dependencies in the controllers, like below:

profileApp.controller('mainController', ['$scope', 'globalParams', function($scope, globalParams){
    //some code

And you can call the functions for getting and setting the variables.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download