Js: Is. value()是设置 app wide 常量的正确方法,以及如何在控制器中检索它

嗨,我看了一些 angular.js 的视频,看到 value ()方法被用来设置一种模块范围的常量。例如,可以这样设置 Angular-UI 库的配置:

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 的 google 组上读到,共享通用代码 btwn 控制器的一种方式是通过一个服务,这个概念也适用于这里吗?

谢谢!

95375 次浏览

You need to reference csrf in your controller IndexUsersCtrl = ( $scope, csrf )

IndexUsersCtrl.$inject = [ '$scope', 'csrf' ]

Module.value(key, value) is used to inject an editable value, Module.constant(key, value) is used to inject a constant value

The difference between the two isn't so much that you "can't edit a constant", it's more that you can't intercept a constant with $provide and inject something else.

// 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
});

I recently wanted to use this feature with Karma inside a test. As Dan Doyon points out the key is that you would inject a value just like a controller, service, etc. You can set .value to many different types - strings, arrays of objects, etc. For example:

myvalues.js a file containing value - make sure it is including in your karma conf file

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 - maybe this is a Jasmine spec file loaded by Karma

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);
});
});