angular组件中的模板没有按预期工作

Template in angular component not working as expected.

本文关键字:工作 组件 angular      更新时间:2023-09-26

这是我的index.html文件。

<!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="app.js"></script>
        <script src="phone-list.component.js"></script>
      </head>
      <body>
        <!-- Use a custom component to render a list of phones -->
        <phone-list></phone-list>
      </body>
    </html>

这是我的phone-list.component.js文件

// Register 'phoneList' component, along with it's associated controller and template'
angular.
  module('phonecatApp').
  component('phoneList', {
    template: 
      '<ul>' + 
      '<li ng-repeat="phone in $ctrl.phones">' + 
      '<span>{{phone.name}}</span>' + 
      '<p>{{phone.snippet}}</p>' + 
      '</li>' + 
      '</ul>' + '<h3>To be honest, my real name is {{me.name}}</h3>', 
      controller: function phoneListController() {
        this.phones = [
          {
            name:'Nexus 5', 
            snippet: 'Fast just got faster with Nexus 5'
          }, 
          {
            name: 'Motorolla Xoom with Wi-Fi', 
            snippet: 'The Next, Next Generation Tablet'
          },
          {
            name: 'Motorolla Xoom', 
            snippet: 'The Next, Next Generation Tablet'
          }
        ];
        this.me = [
          {
            name: 'shameem',
            age: 18
          }
        ]
      }
  });

me.name应该显示在index.html页面的phone-list组件中。我不明白为什么我的名字没有显示在页面上。

请使用以下代码

'</ul>' + '<h3>To be honest, my real name is {{$ctrl.me[0].name}}</h3>', 

代替

'</ul>' + '<h3>To be honest, my real name is {{$ctrl.me.name}}</h3>', 

这个问题是因为你正在使用数组对象并试图直接访问它。或者你可以使用ng-repeat

Or Else Make

this.me =  {name: 'shameem', age: 18}

代替

this.me =  [{name: 'shameem', age: 18}]

和可以使用相同的HTML,如果你改变"this。