Shayan Khan Shayan Khan - 1 month ago 6
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>
</a>
</div>
</div>
</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>

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

<div class="col-md-3">
<div>Some HTML stuff</div>
</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) {

$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){

console.log($routeParams.id);

}]);

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

console.log($routeParams.id);

}]);


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!

Thanks

Answer

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.