简体   繁体   中英

Angular2 displaying data example not working

I am following the tutorial on Angular2 from https://angular.io/docs/js/latest/guide/displaying-data.html but it is not working for me. Let me know what I am missing here.

BTW - I am using ES5 only.

Code in index.html -

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angular2 Demo</title>

    <!-- 1. Load libraries -->
    <!-- IE required polyfill -->
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>

    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.umd.js"></script>
    <script src="node_modules/angular2/bundles/angular2-all.umd.js"></script>

    <script src="app/component.js"></script>
</head>
<body>

        <display></display>
</body>
</html>

In component.js -

function DisplayComponent() {
  this.myName = "Alice";
}
DisplayComponent.annotations = [
  new angular.ComponentAnnotation({
    selector: "display"
  }),
  new angular.ViewAnnotation({
    template:
       '<p>My name: {{ myName }}</p>'
  })
];

Error I am getting if I am running idex.html in browser -

ReferenceError: angular is not defined

The sample doesn't seem to be correct... You should use the ComponentMetadata and ViewMetadata object:

function DisplayComponent() {
  this.myName = "Alice";
}

DisplayComponent.annotations = [
  new ng.core.ComponentMetadata({
    selector: "display"
  }),
  new ng.core.ViewMetadata({
    template:
       '<p>My name: {{ myName }}</p>'
  })
];

See this plunkr for more details: https://plnkr.co/edit/biMKXl1WXsgTCxbjwcme?p=preview .

You could also use the ng.core.Component object as described below:

var DisplayComponent = ng.core.
  Component({
    selector: "display"
  })
  .View({
    template:
      '<p>My name: {{ myName }}</p>'
  })
  .Class({
    constructor: function() {
      this.myName = "Alice";
    }
  });

See this plunkr: https://plnkr.co/edit/73Hirx9aqnITZCPonltX?p=preview .

This link could give you some hints:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM