Angular DI Part 4: Provider
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.provider("log", LogProvider);
app.config(["logProvider", function(logProvider) {
logProvider.disableLogging();
}]);
function LogProvider() {
var enabled = true;
this.disableLogging = function() {
enabled = false;
};
this.$get = function() {
if (enabled) {
return {
log: function(msg) {
console.log(msg);
}
};
}
return {
log: function () {}
};
};
}
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) {
...