我有以下 Angular 1.5 组件:
(function () {
'use strict';
angular
.module('EmployeeInformation')
.controller('EmployeeDetailCtrl', EmployeeDetailCtrl)
.component('employeeDetail', EmployeeDetail);
var EmployeeDetail = {
templateUrl: '../views/components/employeeDetail.html',
controller: 'EmployeeDetailCtrl as empdetail',
bindings: {
employee: '<'
}
};
function EmployeeDetailCtrl() { }
})();
根据 Angular 网站上的示例,我认为这是正确的。但是,当我在页面上包含该文件时,收到一条错误消息,指出它无法注册该组件:
[$injector:modulerr] Failed to instantiate module EmployeeInformation due to:
TypeError: Cannot read property 'controller' of undefined
at $CompileProvider.registerComponent [as component]
如果我删除对此组件的引用,页面加载正常。有人知道我做错了什么吗?
编辑:我在同一模块中有一个服务,其组成类似(包装在函数中并且没有空数组 - 见下文),可以正常工作:
(function () {
'use strict';
angular
.module('EmployeeInformation')
.service('EmployeeService', EmployeeService);
EmployeeService.$inject = ['$http'];
function EmployeeService($http) {
var apiPrefix = 'http://dvlemployees/api/employees';
this.find = find;
this.get = get;
this.getOne = getOne;
function find(queryObj) { }
function get() { }
function getOne(empNumber) { }
})();
EDIT2:感谢@Frondor,我发现真正的问题是我在定义它之前在对象上调用angular.component
。将 var EmployeeDetail
部分移至顶部解决了问题。
最佳答案
JavaScript
(function(angular) {
'use strict';
angular.module('EmployeeInformation', [])
.controller('EmployeeDetailCtrl', EmployeeDetailCtrl)
.component('employeeDetail', {
templateUrl: 'view.html',
controller: EmployeeDetailCtrl,
bindings: {
hello: '='
}
});
function EmployeeDetailCtrl(){
this.world = 'World!';
}
})(window.angular);
HTML
<body ng-app="EmployeeInformation">
<!-- components match only elements -->
<div ng-controller="EmployeeDetailCtrl as ctrl">
<h1>
<employee-detail hello="'Hello'"></employee-detail>
</h1>
</div>
</body>
查看.html
<span>{{$ctrl.hello}} {{$ctrl.world}}</span>
即使您的应用没有使用任何依赖项,您也需要在模块名称后指定一个空数组。
实例:
关于javascript - 注册 Angular 1.5 组件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36452537/