74 lines
2.0 KiB
TypeScript
Raw Normal View History

2015-08-20 14:28:25 -07:00
import {CONST_EXPR} from 'angular2/src/core/facade/lang';
import {EventEmitter, ObservableWrapper} from 'angular2/src/core/facade/async';
2015-05-31 12:24:34 -07:00
import {Query, Directive, LifecycleEvent} from 'angular2/metadata';
import {forwardRef, Binding, Inject, Optional} from 'angular2/di';
2015-05-31 12:24:34 -07:00
import {NgControl} from './ng_control';
2015-05-31 12:24:34 -07:00
import {Control} from '../model';
import {Validators, NG_VALIDATORS} from '../validators';
import {setUpControl, isPropertyUpdated} from './shared';
2015-05-31 12:24:34 -07:00
const formControlBinding = CONST_EXPR(new Binding(NgControl, {toAlias: forwardRef(() => NgModel)}));
2015-05-31 12:24:34 -07:00
/**
* Binds a domain model to the form.
*
* # Example
* ```
* @Component({selector: "search-comp"})
* @View({
* directives: [FORM_DIRECTIVES],
* template: `
<input type='text' [(ng-model)]="searchQuery">
* `})
* class SearchComp {
* searchQuery: string;
* }
* ```
*/
2015-05-31 12:24:34 -07:00
@Directive({
selector: '[ng-model]:not([ng-control]):not([ng-form-control])',
bindings: [formControlBinding],
2015-06-17 15:42:07 -07:00
properties: ['model: ngModel'],
events: ['update: ngModel'],
lifecycle: [LifecycleEvent.OnChanges],
exportAs: 'form'
2015-05-31 12:24:34 -07:00
})
export class NgModel extends NgControl {
_control = new Control();
2015-06-16 15:53:52 -07:00
_added = false;
2015-06-17 15:42:07 -07:00
update = new EventEmitter();
2015-05-31 12:24:34 -07:00
model: any;
viewModel: any;
validators: Function[];
constructor(@Optional() @Inject(NG_VALIDATORS) validators: Function[]) {
super();
this.validators = validators;
}
2015-05-31 12:24:34 -07:00
onChanges(c: StringMap<string, any>) {
2015-05-31 12:24:34 -07:00
if (!this._added) {
2015-06-16 15:53:52 -07:00
setUpControl(this._control, this);
this._control.updateValidity();
2015-05-31 12:24:34 -07:00
this._added = true;
}
2015-05-31 12:24:34 -07:00
if (isPropertyUpdated(c, this.viewModel)) {
2015-06-16 15:53:52 -07:00
this._control.updateValue(this.model);
2015-05-31 12:24:34 -07:00
}
}
get control(): Control { return this._control; }
2015-06-16 15:53:52 -07:00
get path(): string[] { return []; }
2015-05-31 12:24:34 -07:00
get validator(): Function { return Validators.compose(this.validators); }
viewToModelUpdate(newValue: any): void {
this.viewModel = newValue;
ObservableWrapper.callNext(this.update, newValue);
}
}