Angular JS - Can I display a module constant in HT

2019-08-06 18:50发布

问题:

I have a module with a constant like this:

angular.module('SampleMod',[])
.constant("VERSION", "2.1");

I want to show the constant value in HTML with something like this:

<p>{{VERSION}}</p>

Is it possible (without passing by the controller)?

回答1:

You can use $rootScope for this, but you would have to assign the value to $rootScope at some point. You could also use a directive that does essentially the same thing.

angular.module('SampleMod',[])
.constant("VERSION", "2.1")
.run(function ($rootScope, VERSION) {
  $rootScope.VERSION = VERSION;
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app=SampleMod>
<p>{{VERSION}}</p>