【发布时间】:2015-02-13 09:16:39
【问题描述】:
我正在学习 Angular,并且仅当所有代码都内联在页面上时,才能将控制器添加到我的模块中。如果我用 <script src="myModuleFile.js"></script> 替换它,它会失败
"错误:[$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>
【问题讨论】:
-
你在缩小你的来源吗?您似乎没有使用
$inject,并且似乎也没有使用依赖项数组。您需要一些方法来注入您的依赖项,否则它们会在缩小时中断。 -
由于您使用的是
var app = angular.module('app', []),您是否正在重新初始化myModuleFile.js中的模块? -
顺便说一句,您是否向我们提供了完整的错误信息?
-
@claies 在任何教程中都没有表明控制器具有依赖关系。当 angularJS 文档位于具有类似错误的外部文件中时,许多关于 angularJS 文档的教程都不起作用。
-
@rebornix javascript 的第一个代码块就是该文件中的内容。我错过了一步吗?是的,这就是完整的信息。
标签: javascript angularjs html angularjs-scope