In Part 1 of the series, we walked through the initial steps of setting up the project and adding all related files. Now, let us focus on the App.js file (remember this is just for demo purpose, you would never want to put all your controller code in one single file, separate them based on the controllers)
You first define the app that was declared in default/
‘use strict’;
var customerApp = angular.module(‘CustomerApplication‘, [‘ngRoute’]);
Now, let us work on the customer Controller
customerApp.controller(‘CustomerListCtrl’, function ($scope, $http) {
$http({ headers: { “Accept”: “application/json; odata=verbose” }, method: ‘GET’, url: “http://tksp15:90/_api/web/lists/getByTitle(‘Customers’)/items?$select=CustomerID1,CustomerName,CustomerAddress,CustomerState,CustomerCountry” })
.success(function (data) {
$scope.customers = data.d.results;
});
console.log(“Customer Controller…”);
});
You will have to get a json back and so you set that using the $http service and relevant header.
Notice the REST API call — I am querying from customers list and getting few columns out of the list. Note that in the real world, you will also pass in authentication parameters to validate the user.
Now, Orders controller
customerApp.controller(‘OrderCtrl’, function ($scope, $routeParams, $http) {
$scope.custID = $routeParams.customerID
$http({ headers: { “Accept”: “application/json; odata=verbose” }, method: ‘GET’, url: “http://tksp15:90/_api/web/lists/getByTitle(‘Orders’)/items?$filter=CustomerID1 eq ” + $scope.custID + “&$select=OrderID,OrderName,OrderDate,OrderShipCountry” })
.success(function (data) {
$scope.orders = data.d.results;
});
console.log(“Order Controller…”);
});
You will notice in the REST API call, that I am passing in the CustomerID1 as a parameter. This is what filters the Orders list and pulls only Order information for that Customer.
Now that we have our controllers, how do we ensure that the routing happens. Here is the code
customerApp.config(function ($routeProvider) {
$routeProvider.
when(‘/’, {
templateUrl: ‘Templates/customer.html’,
controller: ‘CustomerListCtrl’
}).
when(‘/:customerID’, {
templateUrl: ‘Templates/orders.html’,
controller: ‘OrderCtrl’
}).
otherwise({
redirectTo: ‘/’
});
});
Recollect, that in Part 1, we created the html files. Review how these html files are referenced here. If you are familiar with MVC concepts, this should be no brainer. My definition of AngularJS is bringing MVC to the Javascript world. Concepts are pretty much the same. angular-route.js is the brain behind this routing mechanism.
In the next part, let us write up the HTML files and wrap up the series..