AngularJS - 无法在指令中使用工厂方法

AngularJS - Unable to use Factory Method inside Directive

我在尝试将 myFactory 注入 myDirective 时遇到问题。我需要 myfactory.myMethod 来获得基于特定事件的动态 templateUrl

这就是我现在正在尝试的:

(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;

    }]);

})();

我收到以下错误

myFactory.myMethod is not a function

我也尝试在 SO 上查看各种解决方案,但找不到合适的解决方案。

myFactory 是一个简单的工厂

(function () {
  'use strict';

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

      function myMethod() {
       . . .
      }

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

      return {
        myMethod: myMethod
      }

    });
})();

我该如何解决这个问题?

提前致谢。

我想我发现了你的错误,你在 return 模板 url templateUrl : function(myFactory){} 的函数中将服务作为参数传递。完全错误,不能作为参数使用

要更正它,您需要删除 set templateUrl 函数中的 myFactory 参数,例如:

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

而且我看到您的代码缺少创建模块:angular.module('myApp', []);

CodePen.

试试自己

希望对您有所帮助 ;)