Giova.panasiti Giova.panasiti - 5 months ago 15
AngularJS Question

Use parameters with UIRouter and Components

Hello everyone I'm having some problem to use ui router with parameters.

I'm using angularfire and all my datas are in firebase.

//This is my router
.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('home', {
url :'/home',
template :'<home></home>'
})
.state('projects', {
url:'/projects',
template: "<project-list></project-list>"
})
.state('projectDetails',{
url:'/project/:id',
template : '<project-detail></project-detail>'

});
$urlRouterProvider.otherwise('home');
})


And this is the controller inside the component projectList

function ProjectListController($scope, $element, $attrs, $firebaseArray, $stateParams) {
var ctrl = this;


var projects_ref = firebase.database().ref().child("projects");
var projects = $firebaseArray(projects_ref);
});


ctrl.details = function (project) {

//$state.go('project-details', {: project.$id});
console.log(project.$id);
projectId = project.$id;
return projectId;


}


How do i make that ":id" to work? What I basically want is to have page where all the projects are listed and once I click one link i need the url to be something like "example.com/project/{projectId}

Do you have any suggestion for me?

Answer

Change state projectDetails to projects.details. Also, give it it's own controller e.g.:

  .state('projects.details',{
     url:'/project/:id',
     template : '<project-detail></project-detail>'
     controller : 'ProjectDetailsCtrl as projectDetailsCtrl'
  });

And in your ProjectDetailsCtrl, you will have access to the $stateParams. e.g.

.controller('ProjectDetailsCtrl',['$stateParams',function ProjectDetailsCtrl($stateParams){
    console.log($stateParams.id);
}])

Trigger the navigation to the project via a controller using $state.go('projects.detail',{id:projectId}); assuming projectId is a variable with the project id as value. Or via an element using ui-sref="projects.detail({id:projectId}) assuming projectId is available as data to your view.