2

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?

2
  • controller: 'controllerName' should work here. Commented Apr 16, 2015 at 20:21
  • And how would the params get to that controller? And how to access them there? Commented Apr 16, 2015 at 20:22

2 Answers 2

3
.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).

Sign up to request clarification or add additional context in comments.

3 Comments

So you don't have to do anything special in the .state()?
Nope, I don't think you need to do anything special to get parameters value.
Or you need more explanation then check here. github.com/angular-ui/ui-router/wiki/URL-Routing
0

By the way - a cleaner way of doing this is:

angular.extend($scope, $stateParams);

This will copy the $stateParams keys to the $scope you're in.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.