dnnagy
dnnagy

Reputation: 3533

Access controller scope function in factory angularjs

I have a controller, and a factory that is using the controller's functions. The reason I do this, is because I want to use some functionalities in more controllers, depending on the actual $scope My solution would be something lik the code below. However, angular throws an error saying controllerFunction is undefined

EDIT: This code is working! I made a typo somewhere else in the code.

angular.module('myApp')
 .controller('myController', function ($scope, $http, myInterface) {
    var myFactory = new myInterface($scope);
    $scope.controllerFunction = function(){
        // do something 
    }
 })
 .factory('myInterface', function(){
    var self;
    function Interface($scope) {
      this.$scope = $scope;
      self = this;
    }

    Interface.prototype.interfaceFunction = function(){
      self.$scope.controllerFunction(); 
    }
    return Interface;
});

Upvotes: 2

Views: 1911

Answers (2)

Thalaivar
Thalaivar

Reputation: 23632

You could do something like this, The problem with your code is you are passing the $scope, but after that you are defining the function. Note: $scope is an object and not a service which is singleton shared across. Each and every controller has its own $scope.

var myApp = angular.module("myApp", []);
myApp.controller('Ctrl', function($scope, NameService) {

    $scope.callController = function(){console.log("Called controller")};
    $scope.NameService = new NameService($scope);     
});

myApp.factory('NameService', function() {

    //constructor
    function NameService(scope) {
        this._scope = scope;
        this._someFunction()
    }

    //wherever you'd reference the scope
    NameService.prototype._someFunction = function() {
        this._scope.callController();
    }

    return NameService;

});

http://fiddle.jshell.net/5gmnvL6b/

Upvotes: 2

Ved
Ved

Reputation: 12103

You need to pass a callback method to your factory method from controller.

angular.module('myApp')
 .controller('myController', function ($scope, $http, myInterface) {
    myInterface.myMethod(function (){// callback method passed to factory
       $scope.controllerFunction();//will get called from factory via callback
   )}
    $scope.controllerFunction = function(){
        // do something 
    }
 })
 .factory('myInterface', function(){
     var myMethod = function (cb) {
        //your code
        cb();  //calling callback method of controller
     }

  return myMethod;

});

Upvotes: 2

Related Questions