嗨,我看了几个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的google组上读到,共享公共代码btwn控制器的一种方式是通过服务,这个概念也适用于这里吗?
谢谢!
发布于 2012-10-23 00:33:34
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
});
发布于 2013-05-18 23:10:58
我最近想在测试中使用Karma的这个特性。正如Dan Doyon所指出的,关键是您可以像控制器、服务等一样注入一个值。您可以将.value设置为许多不同的类型-字符串、对象数组等。例如:
myvalues.js包含值的文件-确保它包含在您的karma conf文件中
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);
});
});
发布于 2012-10-23 00:27:50
您需要在控制器IndexUsersCtrl = ( $scope, csrf )
中引用csrf
IndexUsersCtrl.$inject = [ '$scope', 'csrf' ]
https://stackoverflow.com/questions/13015523
复制相似问题