简体   繁体   中英

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.

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.

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. 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

it's longish

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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