سؤال

Suppose I want to make this a variable a constant to be shared among controllers in Angularjs;

$webroot = "localhost/webroot/app"

After some investigation, it seems services are the way to do. But what is the best way? Do I use a factory, service, value or something else?

The services.js from angularjs-master-seed is below;

angular.module('myApp.services', []).value('version', '0.1');

How do I modify it to have a constant $webroot that is sharable among controllers?

Can I do the following?

angular.module('myApp.services', [])
        .value('version', '0.1')
        .constant('webroot','localhost/webroot/app');

If it is ok, how do I call it in the controller?

هل كانت مفيدة؟

المحلول 2

If your variable have a constant value or is set once value is the right choice.
You can define it like this:

app = angular.module('myApp', []);
app.value('$webroot', 'localhost/webroot/app');

Now you can inject the service to your controller and use it:

app.controller('myController', ['$scope', '$webroot', function($scope, $webroot) {
  $scope.webroot = $webroot;
}]);

Edit #1
To fit your updated question: You can use a constant the same way as a value:

app = angular.module('myApp', []);
app.constant('$webroot', 'localhost/webroot/app');

app.controller('myController', ['$scope', '$webroot', function($scope, $webroot) {
  $scope.webroot = $webroot;
}]);

نصائح أخرى

Whats happens when you want more constants? How about adding a config object that you can inject wherever needed. As its a single file it's also much easier to have dev.config and prod.config files that can be swapped in and out at build time.

app.factory('Config', function(){
    return{
        webRoot: "localhost/webroot/app",
        moreSettings: "abc"
    };
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top