Communication between controllers in Angular

戏子无情 提交于 2019-12-02 21:05:38

I use functionality-specific shared services to communicate between controllers.

You can create a generic shared service to have a central point to subscribe to and broadcast events, but I find functionality-specific services to be easier to maintain over time, especially as the project and team grows.

aUXcoder

As Samuel said, using a service to sharing data is a recommended method. The idea is that the state of the data are maintained consistently, regardless of any controller. This two articles can give you an idea of "how to" and "why": Sharing Data Between Controllers, The state of angularjs controllers.

-- There is another option to inheritance and share data between your controllers:

var app = angular.module('myApp', []);

    var parent = function($scope){
        $scope.parent = {
             parentData: 'some data'
        }
    };

    // you could do some prototyping as well
//parent.prototype.parent2 = {
//    parentData: 'some more data'
//};

    var child = function($scope){
        parent.call(this, $scope);
        //$scope.parent2 = this.parent2; here is how you access that data.
    };
    child.prototype = Object.create(parent.prototype);
    child.prototype.constructor = child;


app.controller('parent', parent);

app.controller('myController', child);

This approach give you an advantage:

  • Works with siblings scopes and DOM structure is not needed.

You could continue working with the objects creating custom properties, 'freezing' the data variables to persist the same data and ensure data is not modified, etc.

At the end, I prefer to use a service to share data between controllers and use the observer pattern or pub/sub with rootscope emit/on to acknowledge of actions within controllers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!