0

我需要知道从控制器访问变量“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”?

请帮我

4

4 回答 4

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

参考:如何在 AngularJS 指令中访问全局 js 变量

于 2014-06-10T11:19:19.190 回答
0

将您的控制器更改为

function myCtrl($scope) {
    $scope.x =1;
}
于 2014-06-10T10:18:38.983 回答
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。

于 2014-06-10T10:18:47.333 回答
0

1)如果在本地范围内声明了一个变量,那么您必须将它作为参数传递给另一个 javascript 函数。2)在您的情况下,我建议像这样全局声明“x”:

var x;
function myCtrl() {
    x =1;
}
于 2014-06-10T10:20:40.423 回答