3

Let's take the example from AngularJS tutorial

function PhoneListCtrl($scope, $http) {
   $http.get('phones/phones.json').success(function(data) {
      $scope.phones = data;
   });

   $scope.orderProp = 'age';
}

//PhoneListCtrl.$inject = ['$scope', '$http'];

Now, lets say I don't want to hard code the url 'phones/phones.json' and would prefer the page which hosts this controller to inject it, what should be the right way of doing the same in Angular JS?

1 Answer 1

6

There are a lot of ways to do this... the simplest way would just be to use $window, so you'd inject the $window service, and that's basically just the global $window that's been injected. Then you can register those paths as window.path = 'whatever.json'; and you'll be fine:

window.path = 'some/path.json';

function PhoneListCtrl($scope, $http, $window) {
   $http.get($window.path).success(function(data) {
      $scope.phones = data;
   });

   $scope.orderProp = 'age';
}

A more advanced way would be to create a module with a service that you inject into your app, in this case each page would have it's own module:

 //create your module.
 angular.module('configData', [])
   .factory('pathService', function () {
        return {
           path: 'some/path.json'
        };
   });

//then inject it into your app
var app = angular.module('myApp', ['configData']);

app.controller('PhoneListCtrl', function($scope, $http, pathService) {
   $http.get(pathService.path).success(function(data) {
       $scope.phones = data;
   });

   $scope.orderProp = 'age';
});

You can, of course, do anything in between the two. I would suggest taking the path that is the most maintainable while still easy to test.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm a newbie on Angular. Could you explain how the pathService angument is injected in the controller?
angular looks for the name of the argument to the function and "implicitly injects" it. So, when it calls the controller function internally, it does some JS magic to get the argument names, and gets the service object from a list of registered services by that name, then passes it to the function. ... if that makes sense.
What if I re-use the same controller for several small "apps" on a page? I'd like to inject the URL, just not from Javascript, but from the DOM? (URL is in a data- attribute right now.)
@awendt you might want to ask a question here on StackOverflow, because without a code example, I'm not exactly sure what you're asking or what you've tried.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.