How to make an empty .json file that is filled with variable inputs and others (using angularjs)

0

My problem is this: I try to implement an online test with angular js, I want to use a .json file to store the variables but the problem is that, I want the .json to be empty and to be filled with the inputs of the page, is that possible?

Basically this is my .json file:

{
    "datos":[
{
    "nombre":"",
    "apellido":"",
    "sede":"",
    "ci":""
}
    ],
}

These are the variables that I want to show from the code:

<div ng-show="tab == 6">
<!--Resultados obtenidos-->

<h1>Resultados obtenidos </h1><br><br>

<strong>La nota para el usuario: <br>


{{nombre+" "+apellido}}<br>
C.I.{{ci}}<br>
Sede:.{{sede}}<br>
<br><br>
Es:
<br><br>
{{count}}/20 </strong><br><br>

<b>Sobre 100 es:<br><br>
{{(count*100)/20}}/100<br></b><br><br>


<b>Ha tenido {{counterror/10}} errores</b><br><br>
<b style="color:#467FE2">**Los errores se contaran solo si se ha seleccionado la respuesta incorrecta, si no se ha seleccionado ninguna respuesta, el error no se contará**</b><br>
<br><br><br>

<center>

And this is the .js code that corresponds to the .json driver

 misDatos.controller('controladorDatos',function($scope,$http){
            $scope.importar = function(){
                $http.get('datos.json').sucess(function(datos){

                    $scope.informacion = datos;
                });

            }

$scope.importar();

});

And finally this is my full html code:

<html ng-app="miAplicacion">
<head>
      <title>Proyecto prueba de lapso</title>
<script src="js/angular.min.js"></script> <!--Declarando Angular-->
<script src="js/app.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css"> <!--Declarando Bootstrap-->
<link rel="stylesheet" href="css/style.css"> <!--Declarando estilo css-->

<script type="text/javascript">
      // Load the Visualization API and the corechart package.
      google.charts.load('current', {'packages':['corechart']});

      // Set a callback to run when the Google Visualization API is loaded.
      google.charts.setOnLoadCallback(drawChart);

      // Callback that creates and populates a data table,
      // instantiates the pie chart, passes in the data and
      // draws it.
      function drawChart() {


        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'x');
        data.addColumn('number', 'y');
        data.addRows([
          ['Correctas', 20],
          ['Fallidas', 10]
        ]);

        // Set chart options
        var options = {'title':'Resultados',
                       'width':400,
                       'height':300};

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>

<br><br><br>
<img ng src="img/logo.jpg" with="200px" height="200px"><br><br>
<b>Escuela: </b>Computación<br>
<b>Materia: </b>Programación I<br>
<b>Semestre:</b> 2<br>
<b>Fecha: </b> <div ng-controller="fechaController">
   <span id ="fecha">{{CurrentDate | date:'dd-MM-yyyy'}}</span>
</div>
Tiempo transcurrido: <span id="minutos">0</span>:<span id="segundos">0</span>
      </p>

<br><br>
</head>
<body>
<center><br><br>
<div ng-hide="tab == 6"><div ng-hide="tab == 5"><div ng-hide="tab == 4"><div ng-hide="tab == 3"><div  ng-hide="tab == 2"><div ng-hide="tab == 1"><input type="button" ng-click="tab = 0" value="Comenzar" ng-hide="tab == 0"><br></div></div></div></div></div></div>
<!--Parte0, Datos generales-->
<div ng-show="tab == 0">
<center><h2 style="color:#467FE2">Datos Generales</h2></center>

<b style="color:#FF0000">*Campos obligatorios</b><br><br>

<form name="agregarUsuarioForm">


<b>Nombre <b style="color:#FF0000">*</b></b></h5> <input ng-model="nombre" required><br><br>
<b>Apellido <b style="color:#FF0000">*</b></b></h5> <input ng-model="apellido" required><br><br>
<b>Sede: </b><br>
<input type="radio" name="sede" ng-model="sede" value="Los Naranjos">Los Naranjos
<input type="radio" name="sede" ng-model="sede" value="Centro">Centro<br><br>
<b>Cédula de identidad <b style="color:#FF0000">*</b></b></h5> <input ng-model="ci" required><br><br>
<br><br>
<button ng-show="agregarUsuarioForm.$valid" class="btn btn-primary btn-md" ng-click="tab = 1" ng-click="inicio();" onclick="carga()">Siguiente</button>
<br><br><br><br>
</form>

</div>



<!--Parte1-->
<div ng-show="tab == 1">
<center><h2 style="color:#467FE2"> Prueba en Línea </h2></center><br><br>

<h3>Parte 1</h3><br><br>

1.- Los ________________ son una secuencia de pasos lógicos para la solución de un
problema escrita en lenguaje natural.Valor: 2 puntos<br><br>
<input type="radio" name="respuesta" value="correcta" ng-click="count = count + 2" ng-init="count=0">Algoritmos
<input type="radio" name="respuesta" value="incorrecta" ng-click="counterror = counterror + 10" ng-init="counterror=0">Metodos cientificos
<input type="radio" name="respuesta" value="incorrecta" ng-click="counterror = counterror + 10" ng-init="counterror=0">Teoremas de busquedas y respuestas
<input type="radio" name="respuesta" value="incorrecta" ng-click="counterror = counterror + 10" ng-init="counterror=0">Ninguna de las anteriores

<br><br><br>
2.- Los ________ Son difíciles de aprender y manejar ya que no resultan cercanos al ser
humano.Valor: 2 puntos<br><br>
<input type="radio" name="respuesta2" value="correcta" ng-click="count = count + 2">Lenguajes de bajo nivel
<input type="radio" name="respuesta2" value="incorrecta" ng-click="counterror = counterror + 10">Lenguajes de alto nivel
<input type="radio" name="respuesta2" value="incorrecta" ng-click="counterror = counterror + 10">Lenguajes de medio nivel
<input type="radio" name="respuesta2" value="incorrecta" ng-click="counterror = counterror + 10">Ninguna de las anteriores

<br><br><br>

<br><br>
<input type="button" value="Regresar" ng-click="tab = 0">
<input type="button" value="Siguiente" ng-click="tab = 2">
<br><br><br><br>
</div>


<!--Parte2-->
<div ng-show="tab == 2">
<h3>Parte 2</h3><br><br>
3.- El lenguaje de ___________, es el que utiliza el ordenador.
Valor: 2 puntos<br><br>

<input type="radio" name="respuesta3" value="correcta" ng-click="count = count + 2">Lenguaje de bajo nivel
<input type="radio" name="respuesta3" value="incorrecta" ng-click="counterror = counterror + 10">Lenguaje de alto nivel
<input type="radio" name="respuesta3" value="incorrecta" ng-click="counterror = counterror + 10">Lenguaje de medio nivel
<input type="radio" name="respuesta3" value="incorrecta" ng-click="counterror = counterror + 10">Ninguna de las anteriores
<br><br><br><br>

4.- Los _______________ son utilizados para procesar y entender ____________ de un lenguaje.
Valor: 2 puntos<br><br>

<input type="radio" name="respuesta4" value="incorrecta" ng-click="counterror = counterror + 10">Lectores USB, la estructura
<input type="radio" name="respuesta4" value="incorrecta" ng-click="counterror = counterror + 10">Lectores de CD, el rendimiento
<input type="radio" name="respuesta4" value="correcta" ng-click="count = count + 2">Compiladores, la codificación
<input type="radio" name="respuesta4" value="incorrecta" ng-click="counterror = counterror + 10">Ninguna de las anteriores
<br><br><br><br>

<input type="button" value="Regresar" ng-click="tab = 1"></a>
<input type="button" value="Siguiente" ng-click="tab = 3" ng-hide="tab == 7"></a>
<br><br><br><br>
</div>


<!--Parte3-->
<div ng-show="tab == 3">
<h3>Parte 3</h3><br><br>
5.- El lenguaje natural es el lenguaje hablado o escrito por humanos para propósitos
generales de comunicación.<br><br>

<input type="radio" name="respuesta5" value="correcta" ng-click="count = count + 2">Verdadero
<input type="radio" name="respuesta5" value="incorrecta" ng-click="counterror = counterror + 10">Falso

<br><br>
6.- Un algoritmo debe ser: preciso, definido e infinito. Valor: 2 puntos.<br><br>

<input type="radio" name="respuesta6" value="incorrecta" ng-click="counterror = counterror + 10">Verdadero
<input type="radio" name="respuesta6" value="correcta" ng-click="count = count + 2">Falso

<br><br>
<input type="button" value="Regresar" ng-click="tab = 2">
<input type="button" value="Siguiente" ng-click="tab = 4">
<br><br><br><br>
</div>

<!--Parte4-->
<div ng-show="tab == 4">
<h3>Parte 4</h3><br><br>
7.- Los algoritmos cuantitativos se refieren a algoritmos que resuelven problemas cuyo
resultado es numérico.Valor: 2 puntos<br><br>
<input type="radio" name="respuesta7" value="correcta" ng-click="count = count + 2" >Verdadero
<input type="radio" name="respuesta7" value="incorrecta" ng-click="counterror = counterror + 10">Falso
<br><br>
8.- Un lenguaje de alto nivel son difíciles de aprender y permiten despreocuparse de la
arquitectura del ordenador.Valor: 2 puntos<br><br>
<input type="radio" name="respuesta8" value="incorrecta" ng-click="counterror = counterror + 10">Verdadero
<input type="radio" name="respuesta8" value="correcta" ng-click="count = count + 2">Falso
<br><br>
<input type="button" value="Regresar" ng-click="tab = 3">
<input type="button" value="Siguiente" ng-click="tab = 5">
<br><br><br><br>
</div>


<!--Parte5-->
<div ng-show="tab == 5">
<h3>Parte 5</h3><br><br>
9.- Un algoritmo debe ser: Valor: 2 puntos<br><br>
<input type="radio" name="respuesta9" value="incorrecta" ng-click="counterror = counterror + 10">a) Preciso, definido e infinito
<input type="radio" name="respuesta9" value="correcta" ng-click="count = count + 2">b) Preciso, definido y finito
<input type="radio" name="respuesta9" value="incorrecta" ng-click="counterror = counterror + 10">c) Impreciso, definido e infinito
<input type="radio" name="respuesta9" value="correcta" ng-click="counterror = counterror + 10">d) Impreciso, definido y finito

<br><br>
10.- Los tipos de algoritmos son: Valor: 2 puntos<br><br>
<input type="radio" name="respuesta10" value="incorrecta" ng-click="counterror = counterror + 10"> a) De calidad y cualitativos
<input type="radio" name="respuesta10" value="incorrecta" ng-click="counterror = counterror + 10"> b) De cantidad y cuantitativos
<input type="radio" name="respuesta10" value="correcta" ng-click="count = count + 2"> c) Cualitativos y cuantitativos
<input type="radio" name="respuesta10" value="incorrecta" ng-click="counterror = counterror + 10"> d) De cantidad y cualitativos

<br><br>
<input type="button" value="Regresar" ng-click="tab = 4">
<div onclick="detenerse()"><input type="button" value="Enviar" ng-click="tab = 6" onclick="mostrar()" ></div>
<br><br><br><br>
</div>


<div ng-show="tab == 6">
<!--Resultados obtenidos-->

<h1>Resultados obtenidos </h1><br><br>

<strong>La nota para el usuario: <br>


{{nombre+" "+apellido}}<br>
C.I.{{ci}}<br>
Sede:.{{sede}}<br>
<br><br>
Es:
<br><br>
{{count}}/20 </strong><br><br>

<b>Sobre 100 es:<br><br>
{{(count*100)/20}}/100<br></b><br><br>


<b>Ha tenido {{counterror/10}} errores</b><br><br>
<b style="color:#467FE2">**Los errores se contaran solo si se ha seleccionado la respuesta incorrecta, si no se ha seleccionado ninguna respuesta, el error no se contará**</b><br>
<br><br><br>

<center>



<div ng-show="count == 20"><b>Matrícula de Honor.</b>
Felicitaciones, su puntuación a sido la mejor. Ha pasado la prueba satisfactoriamente sin ningun error.
<br><br>
</div>

<div ng-show="count == 19"><b>Sobresaliente</b>
Felicitaciones, su puntuación a sido la sobresaliente. Ha pasado la prueba satisfactoriamente, con pocos errores.
<br><br>
</div>


<div ng-show="count == 18"><b>Sobresaliente</b>
Felicitaciones, su puntuación a sido la sobresaliente. Ha pasado la prueba satisfactoriamente, con pocos errores.
<br><br>
</div>


<div ng-show="count == 17"><b>Sobresaliente</b>
Felicitaciones, su puntuación a sido la sobresaliente. Ha pasado la prueba satisfactoriamente, con pocos errores.
<br><br>
</div>

<div ng-show="count == 16"><b>Aprobado</b>
Felicitaciones, a aprobado. Ha pasado la prueba aunque con algunos errores. Siga así y su calificación sera mejor.
<br><br>
</div>

<div ng-show="count == 15"><b>Aprobado</b>
Felicitaciones, a aprobado. Ha pasado la prueba aunque con algunos errores. Siga así y su calificación sera mejor.
<br><br>
</div>



<div ng-show="count == 14"><b>Aprobado</b>
Felicitaciones, a aprobado. Ha pasado la prueba aunque con algunos errores. Siga así y su calificación sera mejor.
<br><br>
</div>



<div ng-show="count == 13"><b>Aprobado</b>
Felicitaciones, a aprobado. Ha pasado la prueba aunque con algunos errores. Siga así y su calificación sera mejor.
<br><br>
</div>



<div ng-show="count == 12"><b>Aprobado</b>
Felicitaciones, a aprobado. Ha pasado la prueba aunque con algunos errores. Siga así y su calificación sera mejor.
<br><br>
</div>



<div ng-show="count == 11"><b>Aprobado</b>
Felicitaciones, a aprobado. Ha pasado la prueba aunque con algunos errores. Siga así y su calificación sera mejor.
<br><br>
</div>



<div ng-show="count == 10"><b>Aprobado</b>
Felicitaciones, a aprobado. Ha pasado la prueba aunque con algunos errores. Siga así y su calificación sera mejor.
<br><br>
</div>




<div ng-show="count == 9"><b>Reprobado</b>
Usted no ha pasado la prueba. Ha tenido varios errores. Intentelo de nuevo.<br><br>
</div>

<div ng-show="count == 8"><b>Reprobado</b>
Usted no ha pasado la prueba. Ha tenido varios errores. Intentelo de nuevo.<br><br>
</div>

<div ng-show="count == 7"><b>Reprobado</b>
Usted no ha pasado la prueba. Ha tenido varios errores. Intentelo de nuevo.<br><br>
</div>

<div ng-show="count == 6"><b>Reprobado</b>
Usted no ha pasado la prueba. Ha tenido varios errores. Intentelo de nuevo.<br><br>
</div>

<div ng-show="count == 5"><b>Reprobado</b>
Usted no ha pasado la prueba. Ha tenido varios errores. Intentelo de nuevo.<br><br>
</div>

<div ng-show="count == 4"><b>Reprobado</b>
Usted no ha pasado la prueba. Ha tenido varios errores. Intentelo de nuevo.<br><br>
</div>

<div ng-show="count == 3"><b>Reprobado</b>
Usted no ha pasado la prueba. Ha tenido varios errores. Intentelo de nuevo.<br><br>
</div>

<div ng-show="count == 2"><b>Reprobado</b>
Usted no ha pasado la prueba. Ha tenido varios errores. Intentelo de nuevo.<br><br>
</div>

<div ng-show="count == 1"><b>Reprobado<br>
Usted no ha pasado la prueba. Ha tenido varios errores. Intentelo de nuevo.
<br><br>
</div></b>

<div ng-show="count == 0"><b>Reprobado<br>
Usted no ha pasado la prueba. No ha respondido bien niguna pregunta. Intentelo de nuevo.
<br><br>
</b>

</div>

<div id="chart_div">
</div>
<br><br>
<input type="button" value="Cerrar" onclick="window.close()"><br>
</center>



</body>
</html>

The truth is that I do not know much about .json, so I ask if it is possible that the inputs keep these variables or that they are saved not only with inputs but with variables established on the page. And the information that I have read on the internet about the .json are when they are already pre-established. I would greatly appreciate your answers

    
asked by Grecia V. P. Valero 02.04.2017 в 01:16
source

1 answer

1

Precisely the goal of using a framework MVC as Angular is that: that every time you change the view, change the model and vice versa. The model in your case is an object, it does not matter if you have created this object directly in the code or you have read it from the server in JSON format, JSON is no more than a light text format with a literal notation of objects JavaScript , at the end of this file when it is read through the service $http , in your code will be an object. For example, look at the following code with an object created directly in $scope :

$scope.datos = {
    nombre : ""
};

This would have the same result as this:

JSON Code:

{
    "nombre" : ""
}

JavaScript code in the controller

$scope.datos = {};

$http.get("datos.json").then(function (response) {
    $scope.datos = response.data;
});

The only difference between the two is that the first code is not asynchronous and the second one does (needs to read the data of the server object).

Therefore if your view is prepared to use that object as a model, every time you change a data in the view the model will be updated.

Here I leave you the following snippet . By default the object datos contains three empty variables, I have placed a method so that each time you make a change in inputs or select throw a console.log with a representation JSON of the object used as a model . See how the data is filled in:

var app = angular.module("myApp", []);

app.controller("myController", ["$scope", function($scope) {

  $scope.datos = {

    nombre : "",
    edad   : "",
    sexo   : ""

  };

  $scope.traceResults = function() {

    console.log(JSON.stringify($scope.datos));

  };

}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="myController">
    <input name="nombre" ng-model="datos.nombre" ng-change="traceResults()">
    <input name="edad" ng-model="datos.edad" ng-change="traceResults()">
    <select name="sexo" ng-model="datos.sexo" ng-change="traceResults()">
        <option value="">Selecciona</option>
        <option value="m">Masculino</option>
        <option value="f">Femenino</option>
      </select>
  </div>
</div>
    
answered by 02.04.2017 в 02:46