如何在index.html中调用/访问.constant变量(字符串)?

时间:2014-01-10 22:56:05

标签: angularjs

如果有关angularjs中的常量的信息似乎有相当数量,但没有人显示如何在html文件中调用它的示例,特别是index.html。

我的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。它不应该是一个全局变量吗?我只想在应用程序中添加一个版本字符串。

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分:0)

您必须将{myconstant'注入myCtrl。 然后,您可以使用$scope.string = myconstant.string;

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