我有一个项目,其中homeapp.js包含angular.module依赖项:
var HomeApp = angular.module('HomeApp', [
'ngRoute',
'ngCookies',
'HomeControllers',
'metadataControllers',
'MyControllers',
'ScheduleControllers'
]);
HomeApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/schedules', {
templateUrl: 'pages/list_schedule.html',
controller: 'ScheduleControllers'
});
在ScheduleController.js中,我有:
angular.module('ScheduleControllers', []).controller('PhoneListCrl', function($scope) {
$scope.phones = [
{'name': 'Nexus S',
'snippet': 'Fast just got faster with Nexus S.'},
{'name': 'Motorola XOOM with Wi-Fi',
'snippet': 'The Next, Next Generation tablet.'},
{'name': 'MOTOROLA XOOM',
'snippet': 'The Next, Next Generation tablet.'}
];
});
这基本上是角度教程中的代码片段。
在index.html中,我有:
<html lang="en-CA" ng-app="HomeApp">
...
<li id="id_schedule_list" class="header_list"><a href="#schedules" class="link_without_underline">List Schedule</a></li>
...
然后只使用以下代码指向schedules.html:
<div>
<div ng-controller="PhoneListCrl">
<p>{{phones}}</p>
</div>
</div>
然而,当从浏览器打开html时,它会直接显示{{phones}},而无法显示完整的json对象。控制台说
https://docs.angularjs.org/error/ng/areq?p0=ScheduleControllers&p1=not%20a 1.#QNAN0unction%2C%20got%20undefined
这对我来说没有意义,但我想这是说ScheduleControllers未定义。
在angluar的教程中,app.js说:
var phonecatApp = angular.module('phonecatApp', [
'ngRoute',
'phonecatAnimations',
'phonecatControllers',
'phonecatFilters',
'phonecatServices'
]);
然后在controllers.js中,它有:
var phonecatControllers = angular.module('phonecatControllers', []);
phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone',
function($scope, Phone) {
$scope.phones = Phone.query();
$scope.orderProp = 'age';
}]);
看起来我几乎完全按照教程所做的那样,但为什么它对我不起作用?
答案 0 :(得分:4)
问题实际上与路线有关。您正在使用控制器的模块名称而不是实际的控制器名称。
您拥有controller: 'ScheduleControllers'
,而您需要controller: 'PhoneListCtrl'
。此外,您粘贴的代码在控制器定义中有拼写错误。
angular.module('ScheduleControllers', []).controller('PhoneListCtrl', function($scope) `
修改强>
在下面的代码中,您将告诉角度在您访问/ schedules路由时要加载哪个控制器。现在,它指向&#39; ScheduleControllers&#39 ;,这是一个模块,而不是控制器。改变它以匹配第二个块,你应该很高兴。
HomeApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/schedules', {
templateUrl: 'pages/list_schedule.html',
controller: 'ScheduleControllers'
});
HomeApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/schedules', {
templateUrl: 'pages/list_schedule.html',
controller: 'PhoneListCtrl'
});
答案 1 :(得分:2)
您正在将控制器连接到另一个Angular模块:
// This line creates a new module named "ScheduleControllers"
// And attaches the "PhoneListCrl" to it.
angular.module('ScheduleControllers', []).controller('PhoneListCrl', function() { ... });
如果您希望HomeApp
看到它,请将其附加到该模块:
// You need to attach "PhoneListCrl" to your original module.
angular.module('HomeApp').controller('PhoneListCrl', function() { ... });
答案 2 :(得分:1)
controller: 'ScheduleControllers'
是模块的名称而不是控制器,因此问题