0

I need to know to access the variable ''x" from controller

Javascript

function myCtrl() {
    var x =1;

}

Jasmine

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

how to access the variable ''x" from controller?

please help me

AlexAnand
  • 169
  • 4
  • 18

4 Answers4

0

change your controller to

function myCtrl($scope) {
    $scope.x =1;
}
Jeetendra Chauhan
  • 1,977
  • 2
  • 15
  • 21
0
function myCtrl() {
    var x =1;

}

You cant,x scope is the function,you cant access it from outside.Several choices.

function myCtrl(){
  this.x=1;
}

or

function  myCtrl($scope){
   $scope.x=1;
}

then

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

or

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

if x is meant to be private then dont test it.Test only public APIs.

mpm
  • 20,148
  • 7
  • 50
  • 55
0

1) If a variable is declared in the local scope then You'll have to pass it as a parameter to the other javascript function. 2) In your case i would suggest to declare 'x' globally like this :

var x;
function myCtrl() {
    x =1;
}
BaN3
  • 435
  • 1
  • 3
  • 16
  • yes I declared the var x as globally, how to write unit test for this . to access the variable x – AlexAnand Jun 10 '14 at 10:28
  • `yes I declared the var x as globally,` no you didnt,x is local and private to myCrl in your question . – mpm Jun 10 '14 at 10:36
0

simple example

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

reference: How to access global js variable in AngularJS directive

Community
  • 1
  • 1