AngularJS controller depending on URL parameter

EDIT: Added $ routeProvider and $ routeParams, but $ routeParams.productId is always undefined. This was my initial attempt, but I thought it was the wrong way. In any case, this does not work at the moment.

I'm starting to learn AngularJS, and I have a very simple question: Depending on the identifier contained in the url, I would like to display another BD entry.

... <div ng-app=MyApp> <div ng-controller="MyCtrl"> {{ record }} </div> </div> ... 

My Javascript File:

 var MyApp = angular.module("MyApp",[]); MyApp.config(['$routeProvider', function($routeProvider) { $routeProvider .when('/get/:productId', { controller: 'MyCtrl' }); }]) MyApp.controller('MyCtrl',['$scope','$routeParams','$http', function($scope,$routeParams,$http) { $http.get("/get/"+$routeParams.productId).success(function(data) { $scope.record = data; }); }]) 

I tried using $ routeProvider and $ routeParams without success.

Thanks in advance, Bill

+7
source share
1 answer

you need 2 things, $ routeParams entered into your controller, and creating a valid route using the get method

  MyApp.controller('MyCtrl',['$scope','$http',"$routeParams", function($scope,$http,$routeParams) { $http.get("/get/"+$routeParams.productId).success(function(data) { $scope.record = data; }); }; 
+10
source

All Articles