2014-01-10 35 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> 
相關問題