双向绑定AngularJs2

时间:2015-09-27 16:02:50

标签: angular

此示例失败:

app.ts:

/// <reference path="typings/angular2/angular2.d.ts" />

import { Component, View, Directive, EventEmitter,bootstrap } from 'angular2/angular2';

@Directive({
  selector: '[ng-model]',
  properties: ['ngModel'],
  events: ['ngModelChanged: ngModel'],
  host: {
    "[value]": 'ngModel',
    "(input)": "ngModelChanged.next($event.target.value)"
  }
})
class NgModelDirective {
  ngModel:any; // stored value
  ngModelChanged:EventEmitter; = new EventEmitter() // an event emitter
}

@Component({
  selector: 'my-app'  
})
@View({
    templateUrl: 'index.html',
    directives : [NgModelDirective]
})
// Component controller
class MyAppComponent {  
  constructor(){    
  }
}
// Start my application
bootstrap(MyAppComponent);

Index.html:

<html>
  <head>
    <title>Angular 2 Quickstart</title>    
    <script src="node_modules/angular2/node_modules/traceur/bin/traceur.js"></script>
    <script src="node_modules/systemjs/dist/system.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>    
  </head>
  <body>
    <my-app>
        <input [(ng-model)]="val" ></input>
        Hi {{val}}
    </my-app>
    <script>
      System.import('app.js');
    </script>
  </body>
</html>

StackTrace:

angular2.dev.js:25219 TypeError: Cannot read property 'observer' of undefined
    at Function.execute.ObservableWrapper.subscribe (angular2.dev.js:22638)
    at EventEmitterAccessor.execute.getter.subscribe (angular2.dev.js:28818)
    at execute.AppViewManagerUtils._setUpEventEmitters (angular2.dev.js:23105)
    at execute.AppViewManagerUtils._hydrateView (angular2.dev.js:23078)
    at execute.AppViewManagerUtils.hydrateRootHostView (angular2.dev.js:22996)
    at execute.AppViewManager.createRootHostView (angular2.dev.js:26726)
    at angular2.dev.js:16358
    at Zone.run (angular2.dev.js:136)
    at Zone.execute.$__3._createInnerZone.zone.fork.fork.$run [as run] (angular2.dev.js:16593)
    at zoneBoundFn (angular2.dev.js:109)

1 个答案:

答案 0 :(得分:0)

ngModelChanged:EventEmitter = new EventEmitter() // an event emitter