Best way to override module values/constants in angularJS

前端 未结 3 2356
一个人的身影
一个人的身影 2021-02-20 07:03

I have written a module in angularJS that encapsulates all the backend communications. For greater flexibility I have the api prefix as a constant value on the module (could be

相关标签:
3条回答
  • 2021-02-20 07:48

    Angular modules, controllers, etc. can be contained within functions, if-statements, etc. They do not have to be at the top level. So, you could include this in your code:

    if (environmentOne()) {
      module.value('apiPrefix','api1/data');
    } else {
      module.value('apiPrefix','api2/data');
    }
    

    Hope that helps!

    0 讨论(0)
  • 2021-02-20 07:50

    Our module

    angular.module("data", [])
      .constant('apiPrefix', '/api/data');
    

    We can override constant fully, like value.

    angular.module('myapp', ['data'])
      .constant('apiPrefix', '/api2/data');
    

    also we can override fully in config

    angular.module('myapp', ['data'])
        .config(function ($provide) {
            $provide.constant('apiPrefix', '/api2/data');
        });
    

    also we can override fully or partially (if object) in run

    angular.module('myapp', ['data'])
        .run(function (apiPrefix) {
            apiPrefix = '/api2/data';
        });
    

    But if we want to override constant with object partially in config (not in run), we can do something like this

    angular.module("module1", [])
        .constant('myConfig', {
            param1: 'value1' ,
            param2: 'value2'
        });
    
    angular.module('myapp', ['data'])
        .config(function ($provide, myConfig) {
            $provide.constant(
                'myConfig', 
                angular.extend(myConfig, {param2: 'value2_1'});
            );
        });
    
    0 讨论(0)
  • 2021-02-20 07:52

    to override the module values, you can redefine the angular value in later modules. I believe it should not be done module config time.

    angular.module("data", [])
    .value('apiPrefix', '/api/data')
    .factory('Display', function(apiPrefix){
      return {
        pref: function(){
          return apiPrefix;
        }
      }
    });
    
    
    
    
    angular.module('myapp', ['data'])
      .value('apiPrefix', '/api2/data')
      .controller('MainCtrl', function($scope, Display)    {
          $scope.name = Display.pref();
      });
    

    see the plunker here: http://plnkr.co/edit/k806WE

    same thing is applicable for angular constants too.

    0 讨论(0)
提交回复
热议问题