2014-01-10 34 views
4

如果有关于angularjs中常量的信息,但似乎没有人会在html文件中显示如何调用它的示例,特别是index.html。如何在index.html中调用/访问.constant变量(字符串)?

我app.js有:

.constant('myConstant',{ 
     string:'myString', 
     size: 30 
    }); 

我想我必须有它的控制器(我必须?)。我把它作为'myConstant'包含在myCtrl中。

所以,我已经试过各种事情:

<div ng-controller="myCtrl"> 
    {{string}} 
</div> 

<div ng-controller="myCtrl"> 
    {{myConstant.string}} 
</div> 

<div ng-app"myApp"> 
    {{myConstant.string}} 
</div> 

我只是不知道如何公开此字符串的index.html。它不应该是一个全球变量吗?我只想添加一个版本字符串到应用程序。

+0

你能提供的jsfiddle? –

+0

http://jsfiddle.net/p3N6u/ – letmethink

回答

4

在的jsfiddle,你myConstant是不是在你的$scope

在jsFiddle示例中,myConstant在控制器中可用,但不在视图中,因为它不在$scope中。 $scope是控制器和视图之间的粘合剂。如果你做$scope.myConstant = myConstant;那么它会出现。见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/

+0

我非常新,这将是答案。我希望.constant会做一些神奇的事情,并让它的变量可用于整个应用程序(全局),而不必限制它们,但我现在放弃了角度可以做到这一点的想法。谢谢。 – letmethink

+0

'$ rootScope'会为你做到这一点。不过,如果你打算这么做,我建议创建自定义的“服务”。 –

0

你必须注入'myconstant'到myCtrl。 然后你可以使用$scope.string = myconstant.string;

<div ng-controller="myCtrl"> 
    {{string}} 
</div> 
相关问题