Reputation: 57
There seems to be a fair amount if info about constants in angularjs but nobody shows example of how call it in the html files, specifically index.html.
My app.js has:
.constant('myConstant',{
string:'myString',
size: 30
});
I suppose I have to have it in a controller (do I have to?). I have it being included in myCtrl as 'myConstant'.
So I've tried various things:
<div ng-controller="myCtrl">
{{string}}
</div>
<div ng-controller="myCtrl">
{{myConstant.string}}
</div>
<div ng-app"myApp">
{{myConstant.string}}
</div>
I'm just not sure how to expose this string to index.html. Shouldn't it be a global variable? I just want to add a version string to the app.
Upvotes: 4
Views: 9175
Reputation: 836
In the jsFiddle, your myConstant
was not in your $scope
.
In jsFiddle example, the myConstant is available in the controller but not in the view because it's not in the $scope
. The $scope
is the glue between your controller and the view. If you do $scope.myConstant = myConstant;
then it will appear. See AngularJS Scope Doc
angular.module('myApp.controllers', [])
.controller('myCtrl', ['$scope', '$rootScope', 'myConstant', function ($scope, $rootScope, myConstant) {
$scope.test = "testing...";
$scope.myConstant = myConstant;
console.log(myConstant);
}]);
angular.module('myApp', ['myApp.controllers'] ).constant('myConstant',{
string:'myString',
size: 30
});
jsFiddle: http://jsfiddle.net/p3N6u/1/
Upvotes: 4
Reputation:
You have to inject 'myconstant
' into myCtrl
.
Then you can use $scope.string = myconstant.string;
<div ng-controller="myCtrl">
{{string}}
</div>
Upvotes: 0