Search code examples
angularjsangularjs-scopeangular-http

$scope becomes empty when submitting via post


I am trying to submit $scope.data using post. $scope.data goes empty when passing to a variable.

var token     = angular.element(document.querySelector('meta[name="csrf-token"]')).attr('content');
    console.log("Questions: ");
    console.log($scope.questions);
    var qs = $scope.questions;
    $http({
      url: '/admin/exam/questions/store',
      method: 'POST',
      data: {questions: qs, _token:token}
    });

console.log 2

console.log

Plunker


Solution

  • The problem lies with your choice of starting data type for $scope.q. It's being initialised as an array, like $scope.q = [];. You're then adding properties to that array, like in your question input control with this model binding: ng-model="q.question". But when $scope.q is serialised to JSON, those extra properties are ignored.

    Instead of initialising q as an Array, initialise it as an Object, like: $scope.q = {}.

    You can diagnose the JSON representation of the q object by adding the following expression in your view: {{q | json}}.