0

I want t expose images storage URL to views so I can use it like this in all my views:

<img ng-src="{{storageUrl}}/logo.png"

Right now I have config service which I inject in my every controller, and then expose storageUrl variable to view via $scope.

  angular.module('myApp').controller('MyCtrl', [
    '$scope',
    'AppConfigService',
    function ($scope, AppConfigService) {
        $scope.storageUrl = AppConfigService.storageUrl;
    }

But the problem is that almost in every controller I need to inject this service and expose this varialbe to the view. I don't want to duplicate code so much. So i'm intersting in other ways to globally expose some config variable to the ALL views. What you can suggest?

Thanks

2 Answers 2

3

The "global" scope way

Set it on $rootScope. Although global scope is ill-advised.

Also, if you must use global scope ($rootScope) to track this, you can set it in a run() block, and it will be set as soon as the application is ready:

angular.module('myApp').run([
  '$rootScope', 'AppConfigService', 
  function($rootScope, AppConfigService) {
    $rootScope.storageUrl = AppConfigService.storageUrl
  }
]);

The problem with global scope is that any other modules you load into your app could easily clobber your variable on $rootScope and it will be very hard to debug.

Better way: Use the service directly in an "outer controller":

app.controller('OuterCtrl', [
  '$scope', 'AppConfigService', 
  function($scope, AppConfigService) {
    $scope.config = AppConfigService;
  }
]);

Then wrap your whole app in that controller:

<body ng-controller="OuterCtrl">
  <div ng-controller="MyCtrl"> other stuff here </div>
</body>

Why does this work? Because all controllers and directives under this controller prototypically inherit their scope from this controller's scope.

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

Comments

2

One option is to create a directive for this, and use that directive everywhere instead of ng-src. Something like this:

myModule.directive('mySrc', ['AppConfigService', function(AppConfigService) {
    return {
        restrict: 'A',
        compile: function(element, attrs) {
            element.attr('src', AppConfigService.storageUrl + attrs.mySrc);
        }
    };
}]);

Then you can just use relative paths for your images everywhere

<img my-src="/logo.png" />

Comments

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.