-1

i have two controllers in my codes and in one there is an array.I want to use this array from other controller but it does not work.

I have simplified the codes to make them understandable.

My first controller;

app.controller('mycont1', ['$scope','$timeout', function($scope, $timeout) {

var my;

 my=['1','something',.......];

 }]);

My second controller in directive;

.....,controller: function($scope) {


   var m=my[0];//i want to reach first controller array..

   }

when i call it ,it could not find it.How can i use this array from other controller?

user4773604
  • 451
  • 3
  • 9
  • 16

2 Answers2

2

If you want to share data like this between controllers I suggest you create a service that they can both depend on.

HTML:

<div ng-app="app">
    <p ng-controller="controller1">{{message}}</p>
    <p ng-controller="controller2">{{message}}</p>    
</div>

JavaScript:

var app = angular.module('app', []); 

app.service('dataService', function() {
    return {
        message: 'Hello world!'
    };
}).controller('controller1', function($scope, dataService) {
    $scope.message = dataService.message;
}).controller('controller2', function($scope, dataService) {
    $scope.message = dataService.message;
});

Working fiddle here: https://jsfiddle.net/ben1729/yeLd9rnb/3/

bm1729
  • 2,315
  • 3
  • 21
  • 30
1

For small applications. You can use just $rootScope

saygon91
  • 116
  • 5