[英]Angular.js: Is .value() the proper way to set app wide constant and how to retrieve it in a controller
您好,我正在觀看幾個angular.js視頻,並看到value()方法用於設置一種模塊范圍的常量。 例如,可以像這樣設置Angular-UI庫的配置:(coffeescript)
angular.module('app',[])
.value "ui.config",
tinymce:
theme: 'simple'
width: '500'
height: '300'
我的應用程序目前看起來像這樣:
window.app = angular.module("app", [ 'ui'])
.config(["$routeProvider", ($routeProvider) ->
$routeProvider
.when "/users",
templateUrl: "assets/templates/users/index.html"
controller: IndexUsersCtrl
.otherwise redirectTo: "/users"
])
.value 'csrf', $('meta[name="csrf-token"]').attr('content') #<---- attention here
IndexUsersCtrl = ($scope) ->
$scope.users = gon.rabl
console.log "I want to log the csrf value here" #<---- then attention
IndexUsersCtrl.$inject = ['$scope']
但是我似乎無法通過點擊與app模塊相對應的'app'變量來獲得該值。
我在ST上閱讀了這篇關於angularjs谷歌小組的消息,通過服務分享公共代碼btwn控制器的一種方法是,這個概念也適用於此嗎?
謝謝!
Module.value(key, value)
用於注入可編輯的值, Module.constant(key, value)
用於注入常量值
兩者之間的區別不在於你“不能編輯常量”,更多的是你不能用$ provide攔截常量並注入其他東西。
// define a value
app.value('myThing', 'weee');
// define a constant
app.constant('myConst', 'blah');
// use it in a service
app.factory('myService', ['myThing', 'myConst', function(myThing, myConst){
return {
whatsMyThing: function() {
return myThing; //weee
},
getMyConst: function () {
return myConst; //blah
}
};
}]);
// use it in a controller
app.controller('someController', ['$scope', 'myThing', 'myConst',
function($scope, myThing, myConst) {
$scope.foo = myThing; //weee
$scope.bar = myConst; //blah
});
我最近想在測試中使用此功能與Karma。 正如Dan Doyon指出的那樣,關鍵是你會像控制器,服務等那樣注入一個值。你可以將.value設置為許多不同的類型 - 字符串,對象數組等。例如:
myvalues.js包含值的文件 - 確保它包含在您的業力配置文件中
var myConstantsModule = angular.module('test.models', []);
myConstantModule.value('dataitem', 'thedata');
// or something like this if needed
myConstantModule.value('theitems', [
{name: 'Item 1'},
{name: 'Item 2'},
{name: 'Item 3'}
]);
]);
test / spec / mytest.js - 也許這是由Karma加載的Jasmine規范文件
describe('my model', function() {
var theValue;
var theArray;
beforeEach(module('test.models'));
beforeEach(inject(function(dataitem,theitems) {
// note that dataitem is just available
// after calling module('test.models')
theValue = dataitem;
theArray = theitems;
});
it('should do something',function() {
// now you can use the value in your tests as needed
console.log("The value is " + theValue);
console.log("The array is " + theArray);
});
});
您需要在控制器中引用csrf
IndexUsersCtrl = ( $scope, csrf )
IndexUsersCtrl.$inject = [ '$scope', 'csrf' ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.