我想在我的应用程序中共享这样的功能,我几乎没有工厂。问题是,每当需要时,我必须在每个控制器中添加所有这些工厂。随着越来越多的工厂和控制器,这是一个乏味的任务!
因此,我试图找到一种方法来减少这种冗余。在浏览同样的内容时,我遇到了以下问题:
Can I make a function available in every controller in angular?
这就是我要找的,下面的答案看上去最适合我:
https://stackoverflow.com/a/24714658/3375368
现在我想走一步,消除插入$rootScope的需要!
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.run(function($rootScope, myService) {
$rootScope.appData = myService;
});
myApp.controller('MainCtrl', ['$scope', '$rootScope', function($scope, $rootScope){
appData.foo() //This wont work
$rootScope.appDate.foo() //This will work
//Is there a way to remove dependancy on $rootScope??
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="appData.foo()">Call foo</button>
<!-- This works, but I wont be using this, its from original post -->
</body>
</html>另一个问题是这种方法是否好?&它将如何影响工厂数据共享的工作,即是否存在任何缺陷?
发布于 2017-04-03 08:40:50
如果您的服务在$rootScope上,那么它们应该可以从$scope访问。所以不需要包含对$rootScope的依赖
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.run(function($rootScope, myService) {
$rootScope.appData = myService;
});
myApp.controller('MainCtrl', ['$scope', function($scope){
$scope.appData.foo() //This will work
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="appData.foo()">Call foo</button>
<!-- This works, but I wont be using this, its from original post -->
</body>
</html>
但是,将所有这些内容加载到$rootScope上并不是一个好主意。AngularJS的依赖注入系统存在的原因是有原因的,但是如果您真的想避免按预期实际使用服务,那么您可以创建一个包含所有其他服务的聚合服务:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.factory('allMyServices', ['myService', function (myService) {
return {
myService: myService
};
}]);
myApp.controller('MainCtrl', ['$scope', 'allMyServices', function($scope, allMyServices){
allMyServices.myService.foo() //This will work
}]);
</script>
</head>
<body ng-controller="MainCtrl">
</body>
</html>
https://stackoverflow.com/questions/43179832
复制相似问题