JeroenJK JeroenJK - 17 days ago 5
AngularJS Question

Angular stateParams to controller, $urlRouterProvider

I'm building an app with Ionic and AngularJS.

Now I have a page with a list of items. Each item has an ID, and so a click results in something like this:

/item/1


or

/item/2


where 1 and 2 are ID's.

Now I have the default state like this, for the homepage with this list:

.state('app.home', {
url: "/home/",
views: {
'menuContent': {
templateUrl: "app/home.html"
},
},
controller: 'HomeCtrl'


})

What I want is to pass the paramater to the controller. What I found is the following solution, but this isn't working. The reason is that it doesn't know which controller to use (in above example,
HomeCtrl
is specified.).

.state('app.item', {
url: "/item/:id",
views: {
'menuContent': {
templateUrl: "app/item.html"
},
},
controller: function($scope, $stateParams) {
$scope.id = $stateParams.id;
}


})

As you can see
controller
now has a function, but where do I specify the actual controller to use?
Also, is this the right way or is there a better/easier way?

Answer
.controller('controllerName',
    [       '$scope','$stateParams'
    function($scope , $stateParams ) {    
        // 
        $scope.id = $stateParams.id;

In $stateParams.id , id will be name of parameter you define in url(:id).