ArthurH
ArthurH

Reputation: 293

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

I'm trying to learn angularjs and struggling with getting my second component, 'list, to render. Is something wrong with the syntax? Here's the 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>

Here's App.js

angular.module('myModule', [])

.component('app', {

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

})

And here's List.js, the one that won't render:

angular.module('myModule', [])

.component('list', {

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

Upvotes: 0

Views: 1027

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30390

The problem here seems to be that you're re-declaring the myModule module twice. The module is being re-declared twice in each of your .js files, when you do the following:

angular.module('myModule', [])

A subtle "gotcha" in angular is that a new module is declared internally in AngularJS when you pass [] as an second argument to angular.module (see documentation)

Try revising your List.js to this and see if that helps:

/* 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>'
})

Upvotes: 1

Related Questions