1、定义html
如前所述,$scope对象被神秘的注入到了控制器中,实际上,这是由于控制器声明了它须要$scope,因此AngularJS才会建立并注入它。这套依赖管理系统能够这样总结:"为了正常工做,我须要一个依赖(协做对象):我不知道它从哪里来,也不知道它如何建立。我只知道我须要它,因此请为我提供它"。angularjs
AngularJS拥有内建的依赖注入(dependeny injection,DI)引擎,职责以下:yii
2、注册服务ide
AngularJS只链接其认识的对象。所以,接入依赖注入机制的第一步,是将对象注册在模块(module)上。咱们不直接注册对象的实例,而是将对象建立方案抛给依赖注入系统。而后AngularJS解释这些方案以初始化对象,并在以后链接他们,最后成为可运行的项目。this
AngularJS的$provide服务能够注册不一样的对象建立方案。以后$injector服务会解释这些方案,生成完备而可用的对象实例(已经解决好全部的依赖关系)。spa
$injector服务建立的对象成为服务(service)。在整个应用的生命中,每种方案AngularJS仅解释一次,也就是说,每一个对象仅有一个实例。code
http://www.yiibai.com/angularjs/angularjs_dependency_injection.htmlhtm
五种对象建立方案:对象
2.1 值blog
定义一个名为defaultInput值,能够注入到控制器中
// 定义一个模块 var mainApp = angular.module("mainApp", []); // 建立 value 对象 "defaultInput" 并传递数据 mainApp.value("defaultInput", 5); ... // 将 "defaultInput" 注入到控制器 mainApp.controller('CalcController', function($scope, CalcService, defaultInput) { $scope.number = defaultInput; $scope.result = CalcService.square($scope.number); $scope.square = function() { $scope.result = CalcService.square($scope.number); } });
2.2 服务
定义一个名为CalcService的服务,能够注入到控制器中
//define a module var mainApp = angular.module("mainApp", []); ... //create a service which defines a method square to return square of a number. mainApp.service('CalcService', function(MathService){ this.square = function(a) { return MathService.multiply(a,a); } }); //inject the service "CalcService" into the controller mainApp.controller('CalcController', function($scope, CalcService, defaultInput) { $scope.number = defaultInput; $scope.result = CalcService.square($scope.number); $scope.square = function() { $scope.result = CalcService.square($scope.number); } });
2.3 Factory
//define a module var mainApp = angular.module("mainApp", []); //create a factory "MathService" which provides a method multiply to return multiplication of two numbers mainApp.factory('MathService', function() { var factory = {}; factory.multiply = function(a, b) { return a * b } return factory; }); //inject the factory "MathService" in a service to utilize the multiply method of factory. mainApp.service('CalcService', function(MathService){ this.square = function(a) { return MathService.multiply(a,a); } }); ...
2.4 常量
mainApp.constant("configParam", "constant value");
2.5 Provider
//define a module var mainApp = angular.module("mainApp", []); ... //create a service using provider which defines a method square to return square of a number. mainApp.config(function($provide) { $provide.provider('MathService', function() { this.$get = function() { var factory = {}; factory.multiply = function(a, b) { return a * b; } return factory; }; }); });