Sunny Day
Sunny Day

Reputation: 543

scope not persisting when changing views

Here is my controller...

'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!';
        }
      });

The issue is I have a view that calls submit() successfully, but when I change views, the object that I added in submit() does not persist and $scope.question goes back to initial state of having 2 objects only. How do I solve this?

Upvotes: 0

Views: 351

Answers (1)

user133688
user133688

Reputation: 7064

Use the MVC pattern. Services (models) hold you objects, your Controller is just kinda like an a go between between your objects and your views. Most of the work that's done is generally in your models. In angular services are persistent where as controllers get destroyed and recreated when it's no longer in use.

 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
  }
})

Upvotes: 1

Related Questions