保存后更新模型而不刷新

时间:2015-12-10 21:46:09

标签: angularjs typescript

我在我的应用中构建了一个列表,用户可以添加到该列表中。一旦他们添加了他们的项目并点击了保存按钮,我希望他们添加的项目立即显示在列表中,并且输入框清除。这是我的控制器中的保存功能。当我重新加载页面时它工作正常,但我认为有一种方法可以通过数据库更新模型来绑定。谢谢!

export class QuestionDetailsController {

    public question;
    public answer;
    public id;
    public save() {
        this.answerService.save(this.answer, this.question.id).then(() => { this.$location.path("$location.path") });//how to update models?
    }
    constructor(
        private answerService: MyApp.Services.AnswerService, private $location: angular.ILocationService, private questionService: MyApp.Services.QuestionService, $routeParams: ng.route.IRouteParamsService)
    {
        this.question = this.questionService.get($routeParams["id"])

    }

现在是HTML页面

        <!--<legend id="qdLegend">{{controller.question.title}}</legend>-->
<h2 id="qdLegend">{{controller.question.title}}</h2>
<hr id="qdhr" />
<div id="questionDiv">
    <div class="col-md-7" id="questionBody">
        <p>{{controller.question.userQuestion}}</p><br /><br />

    </div>
</div>

<div class="col-md-7">

    <div id="answerDiv" ng-repeat="a in controller.question.answers">
        {{a.userAnswer}} --answered by {{a.userName}}
    </div>
</div>
<form ng-submit="controller.save()">

    <div>
        <div class="form-group col-md-7" id="answerBox">
            <label class="control-label" for="textarea">Your Answer</label>
            <textarea ng-model="controller.answer.userAnswer" class="form-control" id="textarea1" name="textarea"></textarea>

        </div>
        <div class="form-group">
            <label class="col-md-4 control-label" for="button1id"></label>
            <div class="col-md-8" id="detailsButtons">
                <button type="submit" id="button1id" name="Save" class="btn btn-success">Save</button>
                <button id="button2id" name="button2id" class="btn btn-danger">Cancel</button>
            </div>
        </div>
    </div>
</form>

1 个答案:

答案 0 :(得分:1)

好的,我目前没有正在运行的打字稿编译器,所以我会在这里给你一些提示和一些未经测试的代码。

public save() {
  this.answerService.save(this.answer, this.question.id)
    .then(() => {
      this.question.answers.push(angular.copy(this.answer));
      this.answer = {};
    });
}

当服务返回成功时,您将答案添加到答案的问题列表中。我使用angular.copy()来破坏引用,这样您就可以添加多个答案,而不会引用任何引用问题。 在此之后,我只用空的对象覆盖对象。

这很简单。 AngularJS docs have an example采用相同的风格。

这是一个带有javascript控制器的simplified plunker showing the action。这对你来说应该没有问题。

作为问题的注释,请提供缩小的示例,以便更快地理解您的问题。

相关问题