[Angular 2] Adding a data model

Instead of add todo as a string, we create a data model:

export class TodoModel{
    constructor(
        public title: string = ""
    ){}
}


export class TodoService{
    todos: TodoModel[] = [
        new TodoModel('eat'),
        new TodoModel('sleep'),
        new TodoModel('work')
    ];

    addTodo(value: TodoModel):void {
        this.todos.push(value);
    }
}

 

todoInput.ts

import {Component, View, FORM_DIRECTIVES} from "angular2/angular2";
import {TodoService, TodoModel} from "./todoService";
@Component({
    selector: 'todo-input'
})
@View({
    directives: [FORM_DIRECTIVES],
    template: `
        <form action="" (ng-submit)="onSubmit()">
            <input type="text" [(ng-model)]="todoModule.title">
        </form>
    `
})
export class TodoInput{
    todoModule:TodoModel = new TodoModel();

    constructor(
        //@Inject(TodoService) todoService
        public todoService:TodoService
    ){
        this.todoService = todoService;
    }

    onSubmit(){
        this.todoService.addTodo(this.todoModule);
        this.todoModule = new TodoModel();  // reinit the this.todoModule
    }
}

 

posted @ 2015-10-26 04:07  Zhentiw  阅读(256)  评论(0编辑  收藏  举报