angularjsHow do I use path variables in AngularJS?
Path variables in AngularJS are used to store parameters in the URL. These parameters can be used to pass information to the controller and can be retrieved using the $routeParams service.
Example code
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/users/:userId', {
templateUrl: 'user.html',
controller: 'UserController'
});
});
app.controller('UserController', function($scope, $routeParams) {
$scope.userId = $routeParams.userId;
});
In the above example, we define a route with a path variable userId
and use the $routeParams
service to get the value of userId
in the controller.
Code explanation
var app = angular.module('myApp', ['ngRoute']);
: Declares a new AngularJS application.$routeProvider.when('/users/:userId', {...})
: Defines a route with a path variableuserId
.$scope.userId = $routeParams.userId;
: Retrieves the value ofuserId
using the$routeParams
service.
Helpful links
More of Angularjs
- How can I create an editable AngularJS application?
- How can I prevent XSS attacks when using AngularJS?
- How do I use Angular Zone to run my code?
- How do I use Angular to zip files?
- How do I implement one-way binding in AngularJS?
- How do I use the window.open function with AngularJS?
- How do I use AngularJS to watch for changes in a variable?
- How do I upgrade my AngularJS application?
- How do I use an AngularJS variable in a template?
- How do I use the ui-sref in AngularJS?
See more codes...