2015-07-21 60 views
4

我尝试angular2在ES5方式使用此代码:尝试angular2时未定义角度?

<html> 
    <head> 
      <script src="https://code.angularjs.org/2.0.0-alpha.31/angular2.sfx.dev.js"></script> 
      <script> 
      function AppComponent() {} 

      AppComponent.annotations = [ 
       new angular.Component({ 
         selector: 'my-app' 
       }), 
       new angular.View({ 
         template: '<h1>My first Angular 2 App</h1>' 
       }) 
      ]; 

      document.addEventListener('DOMContentLoaded', function() { 
       angular.bootstrap(AppComponent); 
      }); 
      </script> 
    </head> 
    <body> 
     <my-app></my-app> 
    </body> 
</html> 

在Chrome中我收到讨厌的错误:

Uncaught ReferenceError: angular is not defined 

特别是与这行:

new angular.Component({ 
+0

我外部资源米也卡住了。 Angular 2 [显示数据指南](https://angular.io/docs/js/latest/guide/displaying-data.html)使用这种格式,但我还没有在其他指南中找到它。 –

回答

3

试试这个。

<!DOCTYPE html> 
<html> 

<head> 
     <link rel="stylesheet" href="style.css" /> 
     <script src="https://code.angularjs.org/2.0.0-alpha.31/angular2.sfx.dev.js"></script> 
     <script> 
       function Service() {}; 

       Service.prototype.greeting = function() { 
         return 'hello'; 
       }; 

       var Cmp = ng. 
       Component({ 
         selector: 'cmp', 
         viewInjector: [Service] 
       }). 
       View({ 
         template: '{{greeting}} world!' 
       }). 
       Class({ 
         constructor: [Service, function Cmp(service) { 
           this.greeting = service.greeting(); 
         }] 
       }); 

       document.addEventListener('DOMContentLoaded', function() { 
         ng.bootstrap(Cmp); 
       }); 
     </script> 
</head> 

<body> 
     <cmp></cmp> 
</body> 

</html> 
+1

我不知道这是否正常,但如果我命名“cmp别的东西”,它会给我一个铬错误,“cmp”不匹配任何元素......什么给了?有没有办法隐藏这个错误?因为我包括一个“指令”,因此我不得不使用它吗? – Rolando

+0

我想你错过了任何地方。我已经安装了更新名称为“cmp”的plunker到“anil”,但它的工作。请参阅plnkr示例http://embed.plnkr.co/9Xbw3M/preview –

+0

当角码运行时,角度不存在。所以,扔这是一个错误.. –

0

在这里你走这就是你们的榜样中的jsfiddle

https://jsfiddle.net/rmt7m0km/1/正与角被设置为

<body> 
    <script> 
     function AppComponent() {} 
      AppComponent.annotations = [ 
       new angular.ComponentAnnotation({ 
       selector: 'my-app' 
       }), 
       new angular.ViewAnnotation({ 
       template: '<h1>My first Angular 2 App</h1>' 
       }) 
      ]; 
      document.addEventListener('DOMContentLoaded', function() { 
       angular.bootstrap(AppComponent); 
      }); 
    </script> 
    <my-app></my-app> 
</body> 

我用https://angular.io/guide/setup

0
use ng, not angular 

    function AppComponent() { 
     this.text = 'Hello'; 
    }; 

    AppComponent.annotations = [ 
     new ng.ComponentAnnotation({ 
       selector: 'my-app' 
     }), 
     new ng.ViewAnnotation({ 
       template: '<h1>{{text}}, My first Angular 2 App</h1>' 
     }) 
    ]; 

    document.addEventListener('DOMContentLoaded', function() { 
     ng.bootstrap(AppComponent); 
    });