0

i'm developing for the first time with Angular JS and i'm editing a my friend's app. I would call a factory from a directive that is in another file. Here is the code of the involved files:

user-factory.js

(function() {
  'use strict';

  angular.module('myApp.services').factory('currUserService', function() {
    var curruser = '';
    var self = this;
    return {
      setCurrUser: function(user) {
          self.curruser = user;
      },
      getCurrUser: function() {
          return self.curruser;
      },
    }
  });


}());

mainpage-users-box.js

(function() {
  'use strict';

  angular.module('myApp.directives').directive('mainpageUsersBox', function() {
    return {
      restrict: 'E',
      replace: true,
      scope: {
          users: '=users'
        },
      templateUrl: 'views/templates/mainpage-users-box.directive.html',
      controller: controller,
      controllerAs: 'ctrl'
    };
  });

  function controller($scope) {
    var ctrl = this;

    ctrl.openProfile = function(user) {
      ctrl.currUserService.setCurrUser(user);
    };
  }

  controller.$inject = ['$scope'];

}());

mainpage.html

[...]
<mainpage-users-box users="ctrl.users"></mainpage-users-box>
[...]

As you can see in the second file i want to use .setCurrUser(user) method but i get this error: TypeError: Cannot read property 'setCurrUser of undefined` in the Chrome console.

Can you help me to figure out what could be the reason?

smartmouse
  • 13,912
  • 34
  • 100
  • 166

1 Answers1

0

It doesn't seem like you are injecting the service at all:

// Where's the service?  
function controller($scope) {
    var ctrl = this;

    ctrl.openProfile = function(user) {
      ctrl.currUserService.setCurrUser(user);
    };
  }

  // Where's currUserService?
  controller.$inject = ['$scope'];

Would this not work if you change your controller to this instead?

function controller(currUserService) {
    var ctrl = this;

    ctrl.openProfile = function(user) {
      ctrl.currUserService.setCurrUser(user);
    };
  }

  controller.$inject = ['currUserService'];

You seem to be using the controllerAs style of writing controllers. In this case, you don't need the $scope to be injected, unless you are adding $watches.

Mark
  • 2,137
  • 4
  • 27
  • 42