Monday, 17 July 2017

angularjs - How to pass param in routeProvider in Angular JS?



I use routeProvider in Angular JS:



.when('/profile/personal', {
templateUrl: 'personal.html',
controller: 'EditProfileController'
})


How I can pass param to controller EditProfileController and here call Ajax method that returns data. This data must be display in template of route in personal.html.



Example:



    .controller('EditProfileController', ['$scope', '$http', function ($scope, $http) {
// If was click on `/profile/personal` from route, must get patam `personal` and call method GetAjax(param);
$scope.GetAjax = function (param){
//here return data put it in template HTML from route
}

}]);


My links are located in page by path:



http://wd.tk/profile



When I click to link route I get URL:



http://wd.tk/profile#/profile/personal/1



Id do:



.controller('EditProfileController', ['$scope', '$http', function ($scope, $http, $routeParams) {
console.log($routeParams);
}]);


I get error:



TypeError: Cannot read property 'idProfile' of undefined

Answer



First, in your url configuration, you must put the parameter of url:



when('/profile/personal/:idProfile', {
templateUrl: 'personal.html',
controller: 'EditProfileController'
})


Now, in your EditProfileController, you should get the parameter and call to ajax request:



Inject the $routeParams object and get the parameter with



$routeParams.idProfile:

.controller('EditProfileController',
function ($scope, $http, $routeParams) {

var idProfile = $routeParams.idProfile;

$http.get("service url").then(setData, setError);

function setData(data) {
$scope.data = data;
}
function setError() {
alert("error on get data profile");
}

}]);


In your html, you will show your data profile in the correct format.



But I recommend that all the ajax calls should groups in angular services.
PD:
Check It out angular ui router:



What is the difference between angular-route and angular-ui-router?



hope this helps.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...