简体   繁体   English

控制器Angularjs,服务或父控制器之间的通信

[英]Communication between controllers Angularjs, service or parent controller

I am wondering which is best practise, or perhaps in which situation one way is preferred over the other. 我想知道哪种方法最好,或者哪种情况比另一种方法更可取。

The setup is as follows if we use a parent(main) controller: 如果使用父(主)控制器,则设置如下:

<div ng-controller="Controller Main">
  <div ng-controller="Controller 1"></div>
  <div ng-controller="Controller 2"></div>
</div>

So we can communicate here because both controller 1 and 2 have access to Controller Main's scope. 因此,我们可以在此处进行通信,因为控制器1和2都可以访问Controller Main的范围。

The other way is if we use a service, 另一种方法是,如果我们使用服务,

<div ng-controller="Controller 1"></div>
<div ng-controller="Controller 2"></div>

So what I think we're doing is that we inject the service to the controllers. 因此,我认为我们正在做的是将服务注入控制器。

I've seen both solutions but I don't know which one is preferred. 我已经看过两种解决方案,但我不知道哪种是首选。

It's preferred to use a service. 最好使用服务。 Communicating by using a parent controller breaks encapsulation not to mention it can be pretty buggy if you get someone who doesn't know about the limitations of primitives and scope inheritance etc. Angular's dependency injection works really well and your code will be more flexible in the long run if you do it that way. 使用父控制器进行通信会破坏封装,更何况如果您遇到不了解基元和范围继承等方面的知识的人,它可能会很麻烦。Angular的依赖注入效果很好,并且您的代码将在其中更加灵活如果这样做的话,从长远来看。

Another advantage of a service is code readability. 服务的另一个优点是代码可读性。 If Controller 1 references something in Controller Main the person reading the code may not know where it came from. 如果Controller 1Controller Main引用了某些内容,则读取代码的人可能不知道其来源。 With a service you see it injected, you immediately know where to look for it. 使用您看到的服务注入,您立即知道在哪里寻找它。

You can use like: 您可以像这样使用:

'use strict';
                (function(window, angular, undefined) {
                    'use strict';
                    angular.module('ctrl.parent', [])
                        .controller('ParentController',function (scope) {
                            scope.vocalization = '';
                            scope.vocalize = function () {
                                console.log(scope.vocalization);
                            };
                    });
                })(window, angular);
                angular.module('app',['ctrl.parent'])
                    .controller('ChildCtrl', function($scope,$controller){
                    angular.extend($scope, new $controller('ParentController', {scope:$scope}));
$scope.vocalization = 'CIP CIP';
                });

take a look angularjs-share-config-directives-between-controllers 看一下angularjs-share-config-directives-between-controllers

it's longish 很长

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM