AngularJS : pass data from controller to controlle

2020-03-30 07:24发布

问题:

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.

Factory and service are excluded since i eventually want to migrate my app to angular 2, and i don't want to use ngclick which seems inseperable with broadcast/up/on. If anyone knows how to pass data on the background (without user interaction, like input or ngclick) using broadcasting, it would work aswell :)

What are my options ? Thank you !

回答1:

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.



回答2:

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