如何通过angularjs将服务注入控制器?

时间:2014-02-17 07:46:19

标签: angularjs

我正在通过以下网站http://docs.angularjs.org/guide/dev_guide.services.injecting_controllers

学习angular.js

我尝试在本地服务器上运行代码段。但它失败了。 我认为问题是控制器不知道'通知'工厂。 有人可以帮忙纠正代码吗?谢谢。

HTML

<body ng-app="myApp">
 <div id="simple" ng-controller="myController">
    <p>Let's try this simple notify service, injected into the controller...</p>
    <input ng-init="message='test'" ng-model="message" >
    <button ng-click="callNotify(message);">NOTIFY</button>
    <p>(you have to click 3 times to see an alert)</p>
</div>

JS

 <script>
//MyServiceModule service module
angular.module('MyServiceModule', []).factory('notify', ['$window', function(win) {
    var msgs = [];
    return function(msg) {
    msgs.push(msg);
    if (msgs.length == 3) {
    win.alert(msgs.join("\n"));
    msgs = [];
    }
    };
}]);
//Controller
function myController(scope, notifyService) {
    scope.callNotify = function(msg) {
    notifyService(msg);
    };
}
myController.$inject = ['$scope','notify'];
// How to let the myController know the 'notify' factory in MyServiceModule?

//myApp
angular.module('myApp', [])
.controller('myController',myController);

</script>

1 个答案:

答案 0 :(得分:2)

您的应用必须为其他模块声明依赖:

//myApp
angular.module('myApp', ["MyServiceModule"])
.controller('myController',myController);