我需要知道从控制器
访问变量''x'的Javascript
function myCtrl() {
var x =1;
}
茉莉
describe("myCtrlsettings", function() {
var scope ;
var rootScope;
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller("myCtrl", {
$scope: scope
});
}));
it(" Test ", function(){
expect(x).toBe(1); // what should I write here??
} );
});
如何从控制器访问变量''x?
请帮帮我
答案 0 :(得分:0)
将您的控制器更改为
function myCtrl($scope) {
$scope.x =1;
}
答案 1 :(得分:0)
function myCtrl() {
var x =1;
}
你不能,x范围是函数,你无法从外部访问它。几个选择。
function myCtrl(){
this.x=1;
}
或
function myCtrl($scope){
$scope.x=1;
}
然后
describe("myCtrlsettings", function() {
beforeEach(inject(function($rootScope, $controller) {
this.scope = $rootScope.$new();
this.ctrl = $controller("myCtrl", {
$scope: this.scope
});
}));
it(" Test ", function(){
expect(this.ctrl.x).toBe(1); // what should I write here??
} );
});
或
describe("myCtrlsettings", function() {
beforeEach(inject(function($rootScope, $controller) {
this.scope = $rootScope.$new();
this.ctrl = $controller("myCtrl", {
$scope: this.scope
});
}));
it(" Test ", function(){
expect(this.scope.x).toBe(1); // what should I write here??
} );
});
如果x是私有的,那就不要测试它。只测试公共API。
答案 2 :(得分:0)
1)如果在本地范围内声明了变量,那么您必须这样做 将它作为参数传递给其他javascript函数。 2)在你的情况下,我建议全局声明'x':
var x;
function myCtrl() {
x =1;
}
答案 3 :(得分:0)
简单的例子
HTML:
<section ng-app="myapp" ng-controller="MainCtrl">
Value of global variable read by AngularJS: {{variable1}}
</section>
JavaScript的:
// global variable outside angular
var variable1 = true;
var app = angular.module('myapp', []);
app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
$scope.variable1 = $window.variable1;
}]);