如何使用 angular 1.3 将服务注入提供者
How to inject services into a provider with angular 1.3
在我能找到的所有信息中(包括 angular 文档),将服务注入提供者的方法是通过 $get
方法:
var myApp = angular.module('myApp', []);
myApp.provider('helloWorld', function() {
this.$get = function() {
return {
sayHello: function() {
return "Hello, World!"
}
}
};
});
function MyCtrl($scope, helloWorld) {
$scope.hellos = [helloWorld.sayHello()];
}
这将在 angular 1.2 及以下版本中完美运行:http://jsfiddle.net/1kjL3w13/
尽管切换到angular 1.3,$get
功能完全中断。似乎从 $get
函数返回的任何内容都不再用于实例化提供者,因此现在对注入 f.e 毫无用处。服务。
与上面相同的示例,但使用 angular 1.3:http://jsfiddle.net/duefnz47/
这正是 angular 文档中提供的行为。所以要么文档有误,要么我完全误解了它。我真的不在乎 $get
方法是否像以前一样工作,我只需要能够可靠地将服务注入我的提供者。
问题是您正在使用根据 angular 1.3
无效的全局控制器
所以使用
angular.module('myApp').controller('MyCtrl',function ($scope, helloWorld) {
$scope.hellos = [helloWorld.sayHello()];
});
此处更新fiddle
**
**
希望对您有所帮助:)
在我能找到的所有信息中(包括 angular 文档),将服务注入提供者的方法是通过 $get
方法:
var myApp = angular.module('myApp', []);
myApp.provider('helloWorld', function() {
this.$get = function() {
return {
sayHello: function() {
return "Hello, World!"
}
}
};
});
function MyCtrl($scope, helloWorld) {
$scope.hellos = [helloWorld.sayHello()];
}
这将在 angular 1.2 及以下版本中完美运行:http://jsfiddle.net/1kjL3w13/
尽管切换到angular 1.3,$get
功能完全中断。似乎从 $get
函数返回的任何内容都不再用于实例化提供者,因此现在对注入 f.e 毫无用处。服务。
与上面相同的示例,但使用 angular 1.3:http://jsfiddle.net/duefnz47/
这正是 angular 文档中提供的行为。所以要么文档有误,要么我完全误解了它。我真的不在乎 $get
方法是否像以前一样工作,我只需要能够可靠地将服务注入我的提供者。
问题是您正在使用根据 angular 1.3
无效的全局控制器所以使用
angular.module('myApp').controller('MyCtrl',function ($scope, helloWorld) {
$scope.hellos = [helloWorld.sayHello()];
});
此处更新fiddle
**
** 希望对您有所帮助:)