【问题标题】:Angular2 displaying data example not workingAngular2显示数据示例不起作用
【发布时间】:2016-05-26 04:33:00
【问题描述】:

我正在关注来自https://angular.io/docs/js/latest/guide/displaying-data.html 的关于 Angular2 的教程,但它对我不起作用。让我知道我在这里缺少什么。

顺便说一句 - 我只使用 ES5。

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>

component.js -

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

如果我在浏览器中运行 idex.html 会出现错误 -

ReferenceError: 角度未定义

【问题讨论】:

    标签: javascript html angularjs angular angular2-template


    【解决方案1】:

    示例似乎不正确...您应该使用 ComponentMetadataViewMetadata 对象:

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

    请参阅此 plunkr 了解更多详情:https://plnkr.co/edit/biMKXl1WXsgTCxbjwcme?p=preview

    您还可以使用ng.core.Component 对象,如下所述:

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

    看到这个 plunkr:https://plnkr.co/edit/73Hirx9aqnITZCPonltX?p=preview

    这个链接可以给你一些提示:

    【讨论】:

    • 如果文档不正确,我应该遵循什么?有什么帮助吗? :)
    • 我用更多样本更新了我的答案。也许这是文档中的错字。 Pascal Precht 的文章可能是一个很好的起点 ;-)
    • 感谢您的链接,抱歉没喝咖啡 :)
    • 不用担心 ;-) 事实上,将 ES5 与 Angular2 一起使用的方法正在进步。这就是为什么关于这个主题的文档较少,但 Angular2 的人正在研究这个......
    猜你喜欢
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    相关资源
    最近更新 更多