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


i don't want use service or factory , pass example array of data. access data in parent controller child component.

factory , service excluded since want migrate app angular 2, , don't want use ngclick seems inseperable broadcast/up/on. if knows how pass data on background (without user interaction, input or ngclick) using broadcasting, work aswell :)

what options ? thank !

if have nested components, can access parent's data require

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

now in child controller have access instance of parent controller , can call methods , access it's properties:

this.parent.parentmethod(); 

you have more detailed code in previous answer here:

where should place code used across components/controllers angularjs app?

your other choices:

bindings

just directives' scope or bindtocontroller can bind data , methods through html attributes using bindings propety of component

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

$rootscope

never use store data. works it's not made purpose , lead unmaintainable code.

services

it's common misconception shared data should done through services. true , practice before 1.5 though.

controller inheritance

another bad practice (imo). in classic mvc app nested controllers can inherit parents $controller service:

.controller('maincontroller', function ($scope) {      $scope.logmessage = function(message) {         console.log("message: " + message);     }  })  .controller('servicescontroller', function($scope, $controller) {     $controller('maincontroller', {$scope: $scope}); }); 

broadcast , emit events

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


Comments