-2

I am trying to get started with angular.js but I can't figure out how to inject a simple variable into my controller before testing.

This is my controller:

angular.module("app").controller("SimpleController", SimpleController);

function SimpleController() {
  var vm = this;
  vm.myVar = 1;
  vm.getMyVar = function() {
    return vm.myVar;
  };
}

My test looks like the following:

describe("SimpleController", function() {
  var vm;

  beforeEach(module('app'));

  beforeEach(inject(function($controller, $rootScope) {
    vm = $controller('SimpleController', {
        $scope: $rootScope.$new(),
        myVar: 2
    });
  }));

  it('myVar should be 2 not 1', function() {
    expect(vm.getMyVar()).toEqual(2);
  });
});

I did a lot of google searching but this is really confusing because many people do use $scope in controller and not thisas I do. But I guess the injection of variables should work with this too?

Jonny
  • 33
  • 3

1 Answers1

0

You may want to try writing your controller this way. This will make $scope accessible.

(function () {
   angular.module("app").controller("SimpleController", SimpleController);

   SimpleController.$inject = ['$scope'];
   function SimpleController($scope) {
      $scope.somevar = "something";
   }
})();

I'm sure you've probably came across the documentation, but here is a link to the docs which contains the basics and should at least get you going in the right direction.

Another alternative would be something like this:

app.controller('SimpleController', ['$scope', function($scope) {
   $scope.somevar = "something";
   ....
}]);

When you use $scope, you're making that property publicly available in the view.

Anonymous
  • 1,978
  • 2
  • 28
  • 37
  • Yes, I know the behaviour of `$scope`. In fact it seems like that you can use `$scope` and `this` in parallel (see http://stackoverflow.com/questions/16619740/angular-should-i-use-this-or-scope). Lets say I use `$scope` and structure the controller as you suggested: How can I mock up somevar in my testcase to have another value? – Jonny Sep 04 '15 at 20:41
  • @Jonny var controller = $controller('SimpleController', { $scope: $scope }); $scope.myVar = 'something' – Anonymous Sep 04 '15 at 20:51