Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

javascript - Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

This is my demo using angularjs, for creating a service file, and adding service to a controller.

I have two problems with my demo:

  • One is when I put <script src="HomeController.js"> before <script src="MyService.js"> I get this error,

Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

  • The other is when I put <script src="MyService.js"> before <script src="HomeController.js"> I get the following error,

Error: [$injector:unpr] Unknown provider: MyServiceProvider <- MyService

My source:

File Index.html:

<!DOCTYPE html>
<html >
    <head lang="en">…</head>
    <body ng-app="myApp">
        …
        <div ng-controller="HomeController">
            <div ng-repeat="item in hello">{{item.id + item.name}}</div>
        </div>

        <script src="Scripts/angular.js"></script>
        <script src="Scripts/angular-route.js"></script>

        <!-- App libs -->
        <script src="app/app.js"></script>    
        <script src="app/services/MyService.js"></script>
        <script src="app/controllers/HomeController.js"></script>
    </body>
</html>

File HomeController.js:

(function(angular){
    'use strict';

    var myApp = angular.module('myApp',[]);

    myApp.controller('HomeController',function($scope,MyService){    
        $scope.hello=[];
        $scope.hello = MyService.getHello();
    });
})(window.angular);

File MyService.js:

(function(angular){
    'use strict';

    var myApp = angular.module('myApp',[]);

    myApp.service('MyService', function () {
        var hello =[  {id:1,name:'cuong'},
            {id:2,name:'nguyen'}];
        this.getHello = function(){
            return hello;
        };
    });

})(window.angular);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This creates a new module/app:

var myApp = angular.module('myApp',[]);

While this accesses an already created module (notice the omission of the second argument):

var myApp = angular.module('myApp');

Since you use the first approach on both scripts you are basically overriding the module you previously created.

On the second script being loaded, use var myApp = angular.module('myApp');.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...