简体   繁体   中英

Angular module only works with inline javascript

I am learning Angular and adding a controller to my module only works when all the code is inline on the page. If I replace it with <script src="myModuleFile.js"></script> it fails with

"Error: [$injector:unpr] http://errors.angularjs.org/1.3.11/ $injector/unpr?p0=aProvider%20%3C-%20a%20%3C-%20personController

var app = angular.module('app', [])
.config([function(injectables){
    console.log('configuring app');
}]).run([function(injectables){
    console.log('running app');
}]).controller("personController", function($scope){
    $scope.firstName = "John";
    $scope.lastName = "Doe";
});

<!DOCTYPE html>
<html ng-app="app">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <link rel="stylesheet" href="web/stylesheets/app.css"/>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
        <!-- wont work if I include it this way -->
        <script src="web/js/app.min.js"></script>
        <!-- but works if I put it in here -->
        <script></script>
    </head>
    <body>
        <label>Name:</label>      
        <input type="text"  ng-model="yourName" placeholder="Enter a name here"><hr />      
        <h1>Hello {{ yourName }}!</h1>

        <div ng-init="firstName='John'">
            <p>The name is <span ng-bind="firstName"></span></p>
        </div>

        <p>My first expression: {{ 5 + 5 }}</p>

        <div ng-controller="personController">
            First Name: <input type="text" ng-model="firstName"><br>
            Last Name: <input type="text" ng-model="lastName"><br>
            <br>
            Full Name: {{firstName + " " + lastName}}
        </div>


         <div ng-init="names=[
            {name:'Jani',country:'Norway'},
            {name:'Hege',country:'Sweden'},
            {name:'Kai',country:'Denmark'}]">

            <ul>
              <li ng-repeat="x in names">
                {{ x.name + ', ' + x.country }}
              </li>
            </ul>
        </div>    

        <button ng-click="count = count + 1">Click me!</button>
        <p>{{ count }}</p> 
    </body>
</html>

As Claies mentioned in the comments, the error message looks like it is trying to find a provider for a dependency "a", which is probably a result of minification.

If you do like:

angular.module(..).controller("SomeCtrl", function($scope){});

It might minify $scope to just a . So instead you should use:

angular.module(..).controller("SomeCtrl", ["$scope", function($scope){}]);

Because the string will not be minified, Angular will know which dependency is which. Another way would be to use $injector of course, as Claies also mentioned.

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