注册Angular 1.5组件时出错

时间:2016-04-06 13:25:32

标签: javascript angularjs angularjs-components

我有以下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部分移至顶部可解决问题。

2 个答案:

答案 0 :(得分:3)

的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>

view.html

<span>{{$ctrl.hello}} {{$ctrl.world}}</span>

您需要在模块名称后面指定一个空数组,即使您没有对您的应用程序使用任何依赖项。

实例:

http://plnkr.co/edit/8TbRcg5LBsdlqxLkUccJ?p=preview

答案 1 :(得分:1)

试一试:

(function (angular) {
  '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);
相关问题