2017-06-09 150 views
-1

我想实现John Papa的Angular架构,但我似乎无法得到它的工作。我觉得我失去了一些关于继承如何工作的基础知识。撇开角模块继承

我只是试图从功能模块foo.module.js访问工厂方法=,test.ping,它位于基本应用程序模块中。当我尝试调用的函数,我在控制台得到一个错误: 的ReferenceError:“测试”未定义

//app.js 
(function() { 

angular.module("app", ['app.foo']) 
    .factory('test', [function() { 

     var service = { 
      ping: ping 
     }; 
     return service 
     function ping() { 
      alert('PING Service method called.'); 
     } 
    }]) 
})(); 

//foo.module.js 
(function() { 

angular.module('app.foo', []); 

})(); 

//foo.js 
(function() { 

angular 
    .module('app.foo') 
    .controller('Foo', Foo); 

Foo.$inject = []; 

function Foo() { 
    var vm = this; 
    alert('Foo loaded'); //the alert is working 

    vm.ping = function() { 
     alert('Ping button clicked.'); //the alert is working 
     test.ping(); //this throws console error 
    } 
} 
})(); 

//html 
<body data-ng-controller="Foo as fooCtrl"> 
    <button data-ng-click="fooCtrl.ping()">PING</button> 

回答

2

你忘了在依赖注入添加test服务。

Foo.$inject = []; 

改变这

Foo.$inject = ['test']; 

而且还

function Foo() { 

function Foo(test) { 
+1

这就是它!有道理......就像不得不添加要使用的角度$服务。我知道这是一件简单的事情......迷失在所有的层面上,但是一旦一切都被连接起来并运转起来,这将是值得的。 –