Reputation: 500
I would like to pass some static configuration data from my server (.NET, PHP) to my Angular application. I don't want to call a web service for this.
In this question a javascript block is generated, but I don't want this. How do I pass a value from main html to partials?
What's the best way to do this?
I was thinking of using the ng-init directive for this:
<div data-ng-app="MyApp" data-ng-init="foo='bar'">
Or is there a better way?
Upvotes: 1
Views: 822
Reputation: 52847
Usually static information is configurable and related to some service. If so, I would create a provider (which is just a specialized service) and configure it in your config function.
Here is the Angular documentation on Providers
Create a Provider
myApp.provider('tooltip', function () {
var version;
var author;
this.setVersion= function(value) {
version = value;
};
this.setAuthor = function(value) {
author = value;
};
this.$get = function (/* injectibles go here */) {
return {
version: version,
author: author,
etc...
};
};
});
Configure the Provider
When you inject your provider in your config function, make sure that you append 'Provider':
myApp.config(function(tooltipProvider) {
tooltipProvider.setVersion('1.0');
tooltipProvider.setAuthor('John Smith');
// more configuration of static data
});
Using the Provider
Inject the provider where you need it, and make use of your static data. Here, we are binding the static data to scope so that we can display it in the view.
// JS
app.controller('ctrl', function($scope, tooltip) {
$scope.version = tooltip.version;
$scope.author = tooltip.author;
});
// HTML
<div ng-controller='ctrl'>
Tooltip Plugin: <br />
Version: {{ version }} <br />
Author: {{ author }} <br />
</div>
Upvotes: 1
Reputation: 2667
What I would recommend doing is using constants in angular. This is an example of one that I have used in a project (the @Url.Content part is c#, but I think you will get the idea).
<script>
angular.module('App.ConfigurationSettings', [])
.constant('ApiBaseUrl','@Url.Content("~/api/")')
.constant('WebBaseUrl','@Url.Content("~")');
</script>
and then when we actually use those constants in our service it looks like this:
var app = angular.module('App.BrandService', ['App.ConfigurationSettings']);
app.factory("BrandService", function ($http, $q, ApiBaseUrl) {
return {
getBrand: function (brandId) {
var deferred = $q.defer();
var url = ApiBaseUrl + 'brands/' + brandId + '.json';
return HttpGet($http, url, deferred);
},
getBrands: function () {
var deferred = $q.defer();
var url = ApiBaseUrl + 'brands.json';
return HttpGet($http, url, deferred);
}
};
});
Upvotes: 2