尝试将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不是函数
我尝试在SO上查看各种解决方案,但我找不到合适的解决方案。
myFactory
是一个简单的工厂
(function () {
'use strict';
angular
.module('myApp')
.service('myFactory', function () {
function myMethod() {
. . .
}
//Or
var myMethod = function(){
. . .
}
return {
myMethod: myMethod
}
});
})();
我该如何解决这个问题?
提前致谢。
答案 0 :(得分:1)
我认为我发现了你的错误,就是你将服务作为参数传递给函数,返回模板url templateUrl : function(myFactory){}
。这是完全错误的,你不能将它用作参数。
要更正它,您需要删除set templateUrl函数中的myFactory
参数,如下所示:
templateUrl : function(){
if(myFactory.myMethod()){
return '/app/hello.html'
}
return '/app/world.html'
}
我看到您的代码缺少创建模块:angular.module('myApp', []);
在CodePen中尝试自己。
希望它有所帮助;)