AngularJS: 从另一个组件的模板中渲染一个组件

AngularJS: rendering a component from within the template of another component

我正在努力学习 angularjs 并努力让我的第二个组件“列表”呈现。语法有问题吗?这是 HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Hello World, AngularJS - ViralPatel.net</title>
    <script type="text/javascript"
        src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> 
</head>
<body ng-app="myModule">

    Write some text in textbox:
    <input type="text" ng-model="sometext" />

    <h1>Hello {{ sometext }}</h1>
  <app></app>
  <script src="App.js"></script>
  <script src="List.js"></script>
</body>
</html>

这是App.js

angular.module('myModule', [])

.component('app', {

  template:
    '<div>' +
      '<h1>Hello from App.js</h1>' +
      '<list></list>' +
    '</div>'

})

这里是 List.js,不会呈现的那个:

angular.module('myModule', [])

.component('list', {

  template:
    '<h1>Hello from List.js</h1>'
    '<ul>' +
      '<li>1</li>' +
      '<li>2</li>' +
    '</ul>'
})

这里的问题似乎是您重新声明了 myModule 模块两次。 当您执行以下操作时,该模块在您的每个 .js 文件中被重新声明两次:

angular.module('myModule', [])

angular 中的一个微妙的 "gotcha" 是当您将 [] 作为第二个参数传递给 angular.module 时,在 AngularJS 中内部声明了一个新模块(see documentation)

尝试修改您的 List.js 看看是否有帮助:

/* Remove the [] to prevent myModule from being re-defined. 
   We assume myModule has been defined during the execution of App.js, 
   which should happen before List.js is executed */
angular
.module('myModule') 
.component('list', {

  template:
    '<h1>Hello from List.js</h1>'
    '<ul>' +
      '<li>1</li>' +
      '<li>2</li>' +
    '</ul>'
})