-1

I am working on Angular Routing and have URLs hardcoded directly in my javascript file. However, I would need to keep these URLs in a separate file, where should I keep it preferably? I can't map them with variables in XML or java given that I am working on CQ Adove 5 environment.

  1. Is it possible to do so in another JS file where I can have mapping between variables and URLs as key-value pair? or would it be better to do so in a JSON?

  2. How can I pick up the values from one JS and access in another JS? I would like to have a variable xyz in place of "/content/abc.html".

Code .when('/', { templateUrl: '/content/abc.html', controller: 'tempController' })

to .when('/', { templateUrl: abc, controller: 'tempController' })

Any help would be really appreciated.

user3137592
  • 103
  • 3
  • 14

1 Answers1

1

TemplateUrl takes either a string or a function that returns a string, simply use an anonymous function like so ->

function() {
    return myPartialObject.abc;
}

As to your first issue, why don't you create a factory for myPartialObject which contains all of your template -> string mappings, inject it into the routeprovider and access this for your template urls? It can be in a separate file as you wish and angular takes care of all the injections etc.

Edit - here's a sample file retrieval function

var retrieveFile = function (url) {
    var promise = $http({
        method: 'GET',
        url: url,
        headers: {Accept: '*/*', 'Content-Type': 'application/x-www-form-urlencoded'}
    });
    return promise;
};

So then you'd attach a .then to promise and do what you want with the data ( in your case set the object your service is returning to the json mapping, angular has some pretty nice json functions to help out with this )

retrieveFile("/myjson.json").then(function (data) {
    SetUpMyVariables(data);
}
LiamRyan
  • 1,892
  • 4
  • 32
  • 61
  • Thanks @LinuxN00b. I got your point of using services and then injecting in routeprovider. But inside the service, I'd still need to pass the variable to a function which will then return the desired url back from where? Would you suggest to call a json having variable:url mapping inside the function? – user3137592 Jul 24 '14 at 18:20
  • You can have it as a mapping in the file if that's easier, if you want to read an actual json file then that's done pretty simply as well using $http service, just make sure to do it as part of the factory initialization and to use then to set it to your variable( assuming that it is a static read-once file) – LiamRyan Jul 24 '14 at 18:41
  • updated answer with sample retrieval in case I've misunderstood – LiamRyan Jul 24 '14 at 18:57