简体   繁体   中英

AngularJS. How to expose to view app-level constant?

I want to expose to all my views some app-level config value. What is more elegant way to achieve this? Should I declare some app-level controller on <body> element and on expose my value using $scope.myVal = myVal . Or better to use rootScope for this purpose?

Also in context of this question I want to ask following: is it good practice in AngularJS to exclude to view some simple logic, like building src attribute of img tag:

<img src="{{config.imagesBaseUrl}}{{product.imageFileName}}"

or better to do this concatenation of URL in controller?

You would use a service and inject the service where it's needed, eg:

myApp.service("Config", function() {
    this.myValue = 3;
})

Controller:

myApp.controller("MyCtrl", ["$scope", "Config", function($scope, Config) {
    $scope.myVal = Config.myValue;
}]);

As for the img source question, concatenate in the controller and use ng-src to set the source.

Populating the rootScope is evil as it would be accessed globally through out the angular module. You can create an Angular service (name it global) and have the config values in it.

Angular Service Tutorial

Consider creating a service that fetches and contains your app wide constants. Then inject this service into the controllers. You can then reference these values from within the controller, and use them for whatever you want. One usage of these values would be to create controller ($scope) level variables for use in your template or other code. In our example this could be used to concatenate the url.

This is where Angular's services come in to play!

angular.module("myApp")
  .constant("config", {
     // Configure all the things
  });

Here's the docs on constant as well. Then you can use it anywhere else in the app...

angular.module("myApp")
  .factory("SomeService", function(config) {
     // config.urlBase or whatever
     return {
         doStuff: function() {}
     };
  });

There's also a really cool grunt task that can help you with this stuff too...

http://mindthecode.com/how-to-use-environment-variables-in-your-angular-application/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM