angularjs在子对象的父对象中调用服务注入
我在想办法打电话给服务部 从孩子体内注射进父母体内 我最终得到了angularjs在子对象的父对象中调用服务注入,angularjs,Angularjs,我在想办法打电话给服务部 从孩子体内注射进父母体内 我最终得到了 <div ng-controller="ParentController"> <div ng-controller="ChildController">{{my}}</div> </div> <script> var app = angular.module('myApp', []); app.factory('Data',
<div ng-controller="ParentController">
<div ng-controller="ChildController">{{my}}</div>
</div>
<script>
var app = angular.module('myApp', []);
app.factory('Data',function(){
return {show:function(msg){return msg;}};
});
app.controller('ParentController',function($scope,Data){
$scope.shareService = Data;
});
app.controller('ChildController',function($scope){
$scope.my = $scope.$parent.shareService.show('Hey');
});
</script>
{{my}}
var-app=angular.module('myApp',[]);
应用程序工厂('数据',函数(){
return{show:function(msg){return msg;}};
});
app.controller('ParentController',函数($scope,Data){
$scope.shareService=数据;
});
app.controller('ChildController',函数($scope){
$scope.my=$scope.parent.shareService.show('Hey');
});
我想知道这是否是一个好的做法(可能不是很方便)
或者如果有更好的方法。如果服务独立于父控制器,则可以像在父控制器中一样将服务直接注入子控制器。为什么要在父作用域上创建依赖项
根据定义,服务意味着在控制器、指令和其他服务之间共享。该服务是一个排序导航标题,如.factory('WindowUtils',function($window,CONFIG){return{setTitle:function(str){var title='';var base=CONFIG.site.title;if(typeof str=='undefined'){title=base;}否则{title=base+CONFIG.site.separator+str;}$window.document.title=title;}}}}因此,我将使用它,而不在所有子项中注入。如果在控制器上定义它,子html上定义的所有控制器都将访问该服务,因此您无法控制它。使用服务的原因之一是使依赖项显式化。因为.controller('CompetitiveProductCtrl',function($scope,$location,WindowUtils){WindowUtils.setTitle('Scegli il tuo miele');}).controller('competiteCreateCtrl',function($scope,$location,WindowUtils){WindowUtils.setTitle('Partecipa');})我应该直接在所有控制器中设置它