Search code examples
angularjsangularjs-directivedependency-injectionangularjs-factory

AngularJS - Unable to use Factory Method inside Directive


I'm having a problem when trying to inject myFactory into myDirective. I need myfactory.myMethod to get a dynamic templateUrl based on a certain event.

That's what I'm trying right now:

(function () {
  'use strict';

  angular
    .module('myApp')
    .directive('myDirective', ['myFactory', function (myFactory) {

      var directive = {
        restrict: 'E',
        templateUrl : function(myFactory){
          if(myFactory.myMethod()){
            return '/app/hello.html'
          }
          return '/app/world.html'
        },
        controller       : 'MyController',
        controllerAs     : 'myCtrl',
        bindToController : true
      };

      return directive;

    }]);

})();

I get the following error

myFactory.myMethod is not a function

I tried looking at various solutions also on SO but I wasn't able to find the proper one.

myFactory is a simple Factory

(function () {
  'use strict';

  angular
    .module('myApp')
    .service('myFactory', function () {

      function myMethod() {
       . . .
      }

      //Or
      var myMethod = function(){
       . . .
      }

      return {
        myMethod: myMethod
      }

    });
})();

How can I fix this?

Thanks in advance.


Solution

  • I think I found your mistake, that is you passed the service as a parameter in function that return template url templateUrl : function(myFactory){}. It's totally wrong, you cannot use it as a parameter.

    To correct it, you need to remove myFactory parameter in the set templateUrl function, like that:

    templateUrl : function(){
      if(myFactory.myMethod()){
        return '/app/hello.html'
      }
        return '/app/world.html'
      }
    

    And I see your code is missing creating module: angular.module('myApp', []);

    Try yourself in CodePen.

    Hope it helps ;)