以角度分解对象

时间:2017-10-25 02:20:15

标签: angularjs

对于角度来说,我是相当新的。我试图理解为什么这不起作用:

收到的错误是:

未捕获错误:[$ injector:modulerr]由于以下原因无法实例化模块phonecatApp: 错误:[$ injector:modulerr]由于以下原因导致无法实例化模块phoneList: TypeError:无法读取属性' controller'未定义的

angular.
module('phoneList').
component(name, component);

var name = 'phoneList';
var component = {
    templateUrl: 'phone-list/phone-list.template.html',
    controller: ['$http', function PhoneListController($http) {
        var self = this;
        self.orderProp = 'age';

        $http.get('phones/phones.json').then(function(response) {
            self.phones = response.data;
        });
    }]
};

我该如何解决这个问题?

我知道我可以做到这一点,但我更喜欢如上所述分解对象。请指教

    angular.
  module('phoneList').
  component('phoneList', {
    templateUrl: 'phone-list/phone-list.template.html',
    controller: ['$http', function PhoneListController($http) {
      var self = this;
      self.orderProp = 'age';

      $http.get('phones/phones.json').then(function(response) {
        self.phones = response.data;
      });
    }]
  });

2 个答案:

答案 0 :(得分:1)

var中使用它们之前,您是否尝试过定义名称和组件.component(name, component)?像:

var name = 'phoneList';
var component = {
    templateUrl: 'phone-list/phone-list.template.html',
    controller: ['$http', function PhoneListController($http) {
        var self = this;
        self.orderProp = 'age';

        $http.get('phones/phones.json').then(function(response) {
            self.phones = response.data;
        });
    }]
};

angular.
module('phoneList').
component(name, component);

答案 1 :(得分:-1)

这是index.html。我已经有app.module.js定义了这个

'use strict';

// Define the `phonecatApp` module
angular.module('phonecatApp', [
  'ngRoute',
  'phoneDetail',
  'phoneList'
]);


<!doctype html>
<html lang="en" ng-app="phonecatApp">
  <head>
    <meta charset="utf-8">
    <title>Google Phone Gallery</title>
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="app.css" />
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-route/angular-route.js"></script>
    <script src="app.module.js"></script>
    <script src="app.config.js"></script>
    <script src="phone-list/phone-list.module.js"></script>
    <script src="phone-list/phone-list.component.js"></script>
    <script src="phone-detail/phone-detail.module.js"></script>
    <script src="phone-detail/phone-detail.component.js"></script>
  </head>
  <body>

    <div ng-view></div>

  </body>
</html>

这不是问题。我的例子直接来自angularjs教程,上面只是将组件对象与组件本身分开的区别。