Search code examples
angularjsng-view

how can i use url parameter in controller using angular?


I'm using angular 1.5.0-beta2

i want to be able to read the parameter /cocktail/:cocktail_name

here i define the app and controller:

var app = angular.module('myalcoholist',['ngMaterial','ngRoute']);
app.controller('CocktailController',['$scope','$http', function ($scope,$http) {
    $scope.cocktailStepsRows=null;
        $http({
            method: 'GET',
            url: 'http://api.myalcoholist.com:8888/cocktail/steps/' + $scope.cocktail_name
        }).then(function successCallback(response) {
            $scope.cocktailStepsRows=response.data;
        }, function errorCallback(response) {
            alert('error');
        });

}]);

as you can see i'm trying to append to the api url $scope.cocktail_name

this is how i configure ng-view:

   app.config(['$routeProvider','$locationProvider',
    function($routeProvider,$locationProvider) {
        $locationProvider.html5Mode(true);
        $routeProvider.
        when('/',{
            templateUrl: 'views/index.html',
            controller: 'IndexController'
        }).
        when('/login', {
            templateUrl: 'views/login.html',
            controller: 'LoginController'
        }).
        when('/cocktail/:cocktail_name', {
            templateUrl: 'views/cocktail.html',
            controller: 'CocktailController'
        }).
        otherwise({
            redirectTo: '/'
        });
    }]);

as you can see i configured the route properly to receive the cocktail_name parameter.

now the problem i'm having is that in the controller, $scope.cocktail_name is undefined.

in the view when i print cocktail name

{{cocktail_name}}

I receive the parameter properly. why not in the controller? what am I missing?


Solution

  • You did not copy the parameter value to the scope. Fix it using:

    $scope.cocktail_name = $routeParams.cocktail_name