Angular DI Part 3: Angular

by Jeremy Likness

HTML

<div ng-app="myApp" ng-controller="myController">
    <button ng-click="getCourses()">Get Course</button>
    {{courseMap | json}}
</div>

JavaScript

var app = angular.module("myApp", []);
app.controller("myController", ["$scope", "$injector", function($scope, inj) {
    var _this = this;
    this.$scope = $scope;
    this.inj = inj;
    $scope.getCourses = function() {
        _this.$scope.courseMap = inj.get("courseMap").getCourseMap();
    };
}]);

app.service("courseMap", CourseMap); 
app.service("instructors", Instructors); 
app.service("courses", Courses); 
app.value("log", new Log()); 

function Log() {
    console.log("Log created."); 
    this.log = function(msg) {
        console.log(msg);
    };
}

function Instructors(log) {
    var _this = this,
        instructors = [
            { id: 1, name: "Jeremy Likness" },
            { id: 2, name: "Jeffrey Richter" },
            { id: 3, name: "Jeff Prosise" }
        ];
    this.log = log;
    log.log("Instructors created.");
    this.getInstructors = function() {
        return instructors.slice(0);
    };
    this.getInstructor = function(id) {
        var list = _this.getInstructors(),
            idx;
        for (idx = 0; idx < list.length; idx += 1) {
            if (list[idx].id === id) {
                return list[idx];
            }
        }
        return null;
    };
}
Instructors.$inject = ['log'];

function Courses(log) {
    var _this = this,
        courses = [
            { id: 1, description: "Threading" },
            { id: 2, description: "Windows 8" },
            { id: 3, description: "Angular" }
        ];
    this.log = log;
    log.log("Courses created.");
    this.getCourses = function() {
        return courses.slice(0);
    };
    this.getCourse = function(id) {
        var list = _this.getCourses(),
            idx;
        for (idx = 0; idx < list.length; idx += 1) {
            if (list[idx].id === id) {
                return list[idx];
            }
        }
        return null;
    };
}
Courses.$inject = ['log'];

function CourseMap(log, instructors, courses) {
    var _this = this,
        courseMap = [
           ...