Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I am using NodeJS and AngularJS.

Within Angular I would like to reference a json file and seperate parts of the json into different controllers.

At the moment I am using http.get within the controller (see below).

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

app.controller('introCtrl', function ($scope, $http) {
   $http.get('src/data_json.js').success(function(data) {
    $scope.intro = data;
});

This returns the entire json object within my first controller. However I would like to require the json file, store it as a variable, and have multiple controllers reference different parts.

Is there a way to use nodejs to pass the json file to the angular controller Or is there a better way to require the json file using angular?

Many thanks

share|improve this question
    
Once you get the json in angular app you can communicate that json to other controllers using angular services – V31 Feb 28 '14 at 8:54

A good strategy would be store the http request in a service Service. Then you can made that service avaible to all your controllers by simply inject it.

If your using a REST service you should also consider to use $resource.

share|improve this answer

Thanks - I used a factory service in the end like you suggested...

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

// Setting up a service to house our json file so that it can be called by the controllers
App.factory('service', function($http) {
    var promise;
    var jsondata = {
        get: function() {
            if ( !promise ) {
                var promise =  $http.get('src/data_json.js').success(function(response) {
                    return response.data;
                });
                return promise;
            }
        }
    };
    return jsondata;
});




App.controller('introCtrl', function (service , $scope) {
    service.get().then(function(d) {
        $scope.header = d.data.PACKAGE.ITEM[0]
    })
});

App.controller('secondCtrl', function (service , $scope) {
    service.get().then(function(d) {
        $scope.title = d.data.PACKAGE.ITEM[1]
    })
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.