I'm creating a user profile page using angular/rails. I've set up a StateProvider using ui-router, like so,
$stateProvider
.state('friendprofile', {
url: '/{name}',
views: {
"friendProfile": {
templateUrl: '../assets/angular-app/templates/_friendProfile.html',
controller: 'friendProfileCtrl',
}
},
})
This is the click action from the template,
%a.profile{"ui-sref" => "friendprofile(user)"}
name: {{ user.name }}
Note that I'm passing user
here.
So when the link .profile
is clicked I go to the url http://localhost:3000/#/Jan%20Jansen. So that's working fine.
In my friendProfileCtrl
I have a function that calls a service,
friendProfileService.loadProfile().then(function(response) {
$scope.user_profile = response.data;
console.log ($scope.user_profile)
})
Which calls this service,
app.factory('friendProfileService', ['$http', function($http) {
return {
loadProfile: function() {
return $http.get('/users/4.json');
}
};
}])
Currently I have the return url users/4/.json
hardcoded. Can I get the users id in there somehow? Or do I have to resolve it in the StateProvider?
You could just add id
parameter of user inside state so that it can be easily readable from the $stateParams
.
url: '/{id}/{name}', //assuming user object has `id` property which has unique id.
So while making an ajax you could directly get the user id
from the user object before making an ajax.
Controller
friendProfileService.loadProfile($stateParams.id).then(function(response) {
$scope.user_profile = response.data;
console.log ($scope.user_profile)
})
Factory
app.factory('friendProfileService', ['$http', '$stateParams', function($http) {
return {
loadProfile: function(id) {
return $http.get('/users/'+ id +'json');
}
};
}])