Angular JS Routing

Angular JS Routing

Angular JS provides built in functionality to handles routes. Routes are declared by the $routeProvider which allows for the integration of controllers, templates and additional variables based on the url.

app.js

This requires angular-route.js to be included within your application as is no longer distributed. You can add the module as a dependency by using the following code, but be sure to included the JS file in your app too.

The $routeProvider has  a number of methods that can be utilized depending on your requirements. ‘.when’ accepts a string and an object as parameters. The string relates to the current url and how to react when matched. The object can contain the url for the template and which controller should be used.

”/index/:action’ is an example of a parameter that can be added to a url. In essence they are similar to $_GET[”] in PHP such as ‘?action=’ – See more about this feature in the controller section.

If no routes are matched ‘.otherwise’ can be used to catch and redirect elsewhere.

controllers.js

$routeParams can be utilized to get the additional parameter supplied from the url (and matched in the routing). ‘action’ was the name supplied in the routing and this is the name of the param in this example, though in theory you can use any name you deem fit, just be sure to update your routes accordingly.

index.html

 

 



Leave a Reply

Your email address will not be published. Required fields are marked *


-->