Communication between controllers in Angular

后端 未结 3 1516
栀梦
栀梦 2021-02-03 12:28

I\'m familiar with the following methods to implement communication between controllers.

Are there others? Are there better approaches / best practices?


3条回答
  •  遥遥无期
    2021-02-03 12:35

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

提交回复
热议问题