问题
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?
回答1:
.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).
回答2:
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.
来源:https://stackoverflow.com/questions/29684658/angular-stateparams-to-controller-urlrouterprovider