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.
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:
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: '=' }
...
Never use it to store data. It works but it's not made for that purpose and will lead to unmaintainable code.
It's a common misconception that shared data should be done through services. It was true and good practice before 1.5 though.
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});
});
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.
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