简体   繁体   中英

How to declare and use modules, controllers, services and bootstrap manually in Angular?

i'm trying to build an AngularJS app that has one Controller, one Service and that Bootstraps manually (no ng-app ). The problem is that I keep having an error :

Argument 'AppController' is not a function, got string

HTML

<!DOCTYPE HTML>
<html xmlns:ng="http://angularjs.org">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js" type="text/javascript"></script>
        <script src="inc/bootstrap.js" type="text/javascript"></script>
        <script src="inc/controllers.js" type="text/javascript"></script>
        <script src="inc/services.js" type="text/javascript"></script>
    </head>
    <body ng-controller="AppController">
        [...]
    </body>
</html>

bootstrap.js

angular.element(document).ready(function() {
    angular.bootstrap(document, ['htmlControllerApp']);
});

controllers.js

angular.module('htmlControllerApp', [])
.controller('AppController', 'ConnectionService', ['$scope', function ($scope, ConnectionService) {
    // Code
}]);

services.js

angular.module('htmlControllerApp')
.factory('ConnectionService', ['$rootScope', function ($rootScope) {
    // Code
}]);

Thanks


EDIT - SOLUTION

In controllers.js , use instead :

angular.module('htmlControllerApp')
.controller('AppController', ['$scope', 'ConnectionService', function ($scope, ConnectionService) {
    // Code
}]);

In bootstrap.js , as a "good practice" :

angular.module('htmlControllerApp', []);
angular.element(document).ready(function() {
    angular.bootstrap(document, ['htmlControllerApp']);
});

This will create the module just once in bootstrap.js and AngularJS will try to retrieve it in controllers.js and services.js .

This is the page you're looking for.

https://docs.angularjs.org/api/ng/function/angular.bootstrap

and change this

angular.module('htmlControllerApp', [])
  .controller('AppController', 'ConnectionService', ['$scope', function ($scope,     ConnectionService) {
    // Code
}]);

to this ->

angular.module('htmlControllerApp', [])
  .controller('AppController', ['$scope', 'ConnectionService', function ($scope, ConnectionService) {
    // Code
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM