joshualan
joshualan

Reputation: 2140

How do I access an object in a different module in AngularJS?

I have two modules:

angular.module('test1', [])
    .run(function() {
        var numbers = [1, 2, 3,4];
        // do more operations on numbers here
    });

angular.module('test2', [])
    .run(function() {
        // I want to edit or iterate over numbers here
    });

I want to be able to edit the variable numbers in the test2 module. I'm extremely new to Angular so it seems like the easiest way to do this is to put numbers in $rootscope but that doesn't seem too desirable.

What's the most idiomatic way to achieve this? Do I make numbers a .value()? Do I make it into a service? Do I make 'editor' depend on 'test' (a concept that I am still trying to grasp)?

Upvotes: 0

Views: 111

Answers (2)

Jorawar Singh
Jorawar Singh

Reputation: 7621

You need a service to pass data. Here is an example how you can try it.

var app = angular.module('app', ['access','test1','test2']);
angular.module('access', [])
    .service('accessService', function() {
        this.numbers = [1, 2, 3,4];
        // do more operations on numbers here
    });

angular.module('test1', [])
    .run(function(accessService) {
        var numbers = accessService.number;
        // do more operations on numbers here
    });

angular.module('test2', [])
    .run(function(accessService) {
       accessService.numbers.forEach(function(number){
         console.log(number)
       })
    });

Upvotes: 2

Rathma
Rathma

Reputation: 1313

I think that run blocks are not the place to store data, it is usually a place to do app initialization I guess.

If you have a list of numbers that you want to be used and modified by others, you can use a service that have those numbers as its property and inject that service anywhere you like, and since services are singleton everyone who accesses that service is working with one and only one object.

you can also think an directives, I have numbers in some scope, I create an editor directive that uses two-way data-binding to access and modify that property on the scope.

Hope it helps

Upvotes: 1

Related Questions