Angularj, URL routing and adding a controller for beginners

Angularjs and Url routing and adding a controller for beginners

Intro

This is a quick tutorial on how to add a new controller to your angularjs application.

Just started working with Angularjs.
This is the basis of adding a new controller and wiring it into angularjs.

Awesome tutorial from angularjs. AngularJS tutorial

Summary:

tl;dr

  1. add a when to the app.js. under the $routeProvider.
  2. create the controller-weva.js file and name the controller the same as the when block.
  3. create the weva-view.html same name as in the when block to receive the controller call.
  4. add the controller-weva.js script named in the when block to the index.html
  5. visit the url from the when block.  May have to restart.

Routing file – /app/js/app.js

The routing of Angularjs is done in the /app/js/app.js file.
App.js from the tutorial project

Here is the contents:

angular.module('phonecat', ['phonecatFilters', 'phonecatServices']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/phones', {templateUrl: 'partials/phone-list.html',   controller: PhoneListCtrl}).
when('/phones/:phoneId', {templateUrl: 'partials/phone-detail.html', controller: PhoneDetailCtrl}).
otherwise({redirectTo: '/phones'});
}]);

phonecat matches the angular-app from the index.html file.
PhoneListCtrl is the name of the controller to use for this request.
/phones the url mapping that will map to the PhoneListCtrl.
partials/phone-list.html is the location of the html file to receive the angularjs call after the controller.  The folder name is not required to be named partial.  Maps to /app/partials/phone-list.html.
phone-list.html from tutorial

Header file: /app/index.html

Index is the starting point for your angularjs project.

The module ‘phonecat‘ from the app.js matches the index ng-app tag in index.html of the project.

<html lang=”en” ng-app=”phonecat“>

index.html from the Angularjs tutorial

The controllers are added via adding a script like following snippet.

<script src=”js/controller.js“></script>

Controller “example” file: /app/js/controllers.js

controllers.js from the tutorial project

Snippet of the controllers.js:

function PhoneListCtrl($scope, Phone) {}

The tutorial has 2 controllers in it but you can have separate files which makes it easier to source control.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s