AngularJS : pass data from controller to controller without factory, service or broadcast?

前端 未结 2 2012
太阳男子
太阳男子 2021-01-15 17:29

I don\'t want to use a service or a factory and would like to pass for example an array of data. I would like to access data in my parent controller from my child component.

相关标签:
2条回答
  • 2021-01-15 18:23

    If you have nested components, you can access the parent's data with require

    var child = {
        bindings: {},
        require: {
            parent: '^^parent'
        },
        controller: childController,
        templateUrl: 'child.template.html'
    };
    

    Now in your child controller you have access to an instance of the parent controller and thus can call methods and access it's properties:

    this.parent.parentMethod();
    

    You have some more detailed code in a previous answer here:

    Where should I place code to be used across components/controllers for an AngularJS app?

    Your other choices:

    bindings

    Just like directives' scope or bindToController you can bind data and methods through html attributes using the bindings propety of your component

    <component-x shared="$ctrl.shared"></component-x>
    
    var componentX = {
        bindings: { shared: '=' }
        ...
    

    $rootScope

    Never use it to store data. It works but it's not made for that purpose and will lead to unmaintainable code.

    Services

    It's a common misconception that shared data should be done through services. It was true and good practice before 1.5 though.

    Controller inheritance

    Another bad practice (imo). In a classic MVC app nested controllers can inherit parents with the $controller service:

    .controller('MainController', function ($scope) {
    
        $scope.logMessage = function(message) {
            console.log("Message: " + message);
        }
    
    })
    
    .controller('ServicesController', function($scope, $controller) {
        $controller('MainController', {$scope: $scope});
    });
    

    Broadcast and emit Events

    It's the way to go if the event you're broadcasting makes sense application wide (login, logout...etc.) If you're updating a variable in a component, don't use it.

    0 讨论(0)
  • 2021-01-15 18:28

    I don't want to use a service or a factory and would like to pass for example an array of data

    You can use localStorage/sessionStorage to store and fetch the data

    0 讨论(0)
提交回复
热议问题