更改视图时范围不会持久

时间:2015-06-26 18:39:13

标签: angularjs

这是我的控制器......

'use strict';

    angular.module('funApp')
      .controller('MainCtrl', function ($scope, $http) {
        $scope.choice = null;
        $scope.addQuestionFeedback = '';
        $scope.questions = [];
        $scope.questions = [
            {
                question: "What is your favorite color",
                type: "color"
            },
            {
                question: "What is your favorite food",
                type: "food"
            }
        ];

        $scope.submit = function() {
            this.questions.push(this.addQuestion);
            $scope.addQuestionFeedback = 'Question Successfully Added!';
        }
      });

问题是我有一个成功调用submit()的视图,但是当我更改视图时,我在submit()中添加的对象不会保留,$scope.question会回到初始状态只有2个对象我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

使用MVC模式。服务(模型)可以保存对象,您的控制器就像是介于对象和视图之间。大部分工作通常都在您的模型中。在角度服务中是持久的,因为控制器在不再使用时会被破坏并重新创建。

 angular.module('funApp')
      .controller('MainCtrl', function ($scope, $http, questions) {
    $scope.choice = null;
    $scope.addQuestionFeedback = '';
    $scope.questions = questions.questions;

    $scope.submit = function() {
        questions.questions.push(this.AddQuestion);
        $scope.addQuestionFeedback = 'Question Successfully Added!';
    }
  })

.factory('questions', function () {
  var questions = [
        {
            question: "What is your favorite color",
            type: "color"
        },
        {
            question: "What is your favorite food",
            type: "food"
        }
    ];


  return {
    questions = questions
  }
})