angularjs提供了一个至高无上的依赖注入机制。它提供了一个可注入彼此依赖下列核心组件。
值 工厂 服务 提供者 常值值
值是简单的javascript对象,它是用来将值传递过程中的配置相位控制器。
//define a modulevar mainapp = angular.module(mainapp, []);//create a value object as defaultinput and pass it a data.mainapp.value(defaultinput, 5);...//inject the value in the controller using its name defaultinputmainapp.controller('calccontroller', function($scope, calcservice, defaultinput) { $scope.number = defaultinput; $scope.result = calcservice.square($scope.number); $scope.square = function() { $scope.result = calcservice.square($scope.number); }});
工厂
工厂是用于返回函数的值。它根据需求创造值,每当一个服务或控制器需要。它通常使用一个工厂函数来计算并返回对应值
//define a modulevar mainapp = angular.module(mainapp, []);//create a factory mathservice which provides a method multiply to return multiplication of two numbersmainapp.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); }});...
服务
服务是一个单一的javascript包含了一组函数对象来执行某些任务。服务使用service()函数,然后注入到控制器的定义。
//define a modulevar 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 controllermainapp.controller('calccontroller', function($scope, calcservice, defaultinput) { $scope.number = defaultinput; $scope.result = calcservice.square($scope.number); $scope.square = function() { $scope.result = calcservice.square($scope.number); }});
提供者
提供者所使用的angularjs内部创建过程中配置阶段的服务,工厂等(相angularjs引导自身期间)。下面提到的脚本,可以用来创建,我们已经在前面创建mathservice。提供者是一个特殊的工厂方法以及get()方法,用来返回值/服务/工厂。
//define a modulevar 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; }; });});
常量
常量用于通过配置相位值考虑事实,值不能使用期间的配置阶段被传递。
mainapp.constant(configparam, constant value);
例子
下面的例子将展示上述所有指令。
testangularjs.html
angularjs dependency injection angularjs sample application enter a number: x2 result: {{result}}
结果
在web浏览器打开textangularjs.html。看到结果如下。
