M16 M16 - 6 months ago 259
AngularJS Question

AngularJS: Pass an object into a state using $state.go()

I'm trying to pass an object with

$state.go()
to another state , but the
$stateParams
is not getting populated .
I have tried everything I could find on web and stackoverflow , but none worked for me. thanks in advance for your help.

here is the code :



MyApp.config(function($stateProvider, $urlRouterProvider){
$stateProvider.state('productList', {
views:{
"main_view":{
templateUrl: 'pages/productList.html',
controller: 'productListController'
},
"second_view":{}
}
});

$stateProvider.state('productDetail', {
views:{
"main_view":{
templateUrl: 'pages/productDetail.html',
url:'/productDetail',
params:{
productObj: null
},
controller: 'productDetailController',
},
"second_view":{}
}
});

}
MyApp.controller('productListController',function($state,$scope,$http, $window){
$http
.get('api/item/index')
.then(function (response) {
$scope.items = response.data;
});
$scope.showProductDetails = function(argItem){
console.log(argItem); // will show the argItem object in logs
$state.go('productDetail',{productObj:argItem}); // here is the problem
}
});
MyApp.controller('productDetailController',function($stateParams,$state,$scope){
console.log($stateParams); //Empty
console.log($state.params) //Empty
});

<!-- using AngularJs v1.5.5 and ui-router v0.2.18 -->

<!-- this is pages/productList.html templateUrl page-->
<article ng-repeat="item in items">
<div class="thumbnail">
<a ng-click="showProductDetails(item)" class="btn btn-info">{{item.name}}</a>
</div>
</article>




Answer

the params : {} does not belong to view, but to state:

$stateProvider.state('productDetail', {
  // this, state level, is a right place for params 
  params:{
      productObj: null
  },
  views:{
    "main_view":{
      templateUrl: 'pages/productDetail.html',
      url:'/productDetail',
      // this is wrong place
      // params:{
      //  productObj: null
      // },
      controller: 'productDetailController',
    },
    "second_view":{}
  }
});