Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Controller depending on URL parameter

EDIT: Added $routeProvider and $routeParams, but $routeParams.productId is always undefined. It was my initial try, but I thought it was the wrong way. Anyway it does not work for the moment.

I start to learn AngularJS and I have a very simple question : Depending on ID contained in URL, I would like to display different BD record.

...
<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 to use $routeProvider and $routeParams without success.

Thank you in advance, Bill

like image 385
billdangerous Avatar asked Jan 10 '13 14:01

billdangerous


1 Answers

you need 2 things , the $routeParams injected in your controller and create a valid route with the get method

    MyApp.controller('MyCtrl',['$scope','$http',"$routeParams",
        function($scope,$http,$routeParams) {
             $http.get("/get/"+$routeParams.productId).success(function(data) {
                 $scope.record = data;
        });
    };
like image 153
mpm Avatar answered Oct 17 '22 22:10

mpm