3

This is an AngularJS problem; I have a simple form:

<input type="text" class="form-control" id="qus" placeholder="Enter Question" ng-model="qus">
<input type="text" class="form-control" id="op1" placeholder="Option 1" ng-model="op1">
<label><input type="checkbox" ng-model="correct1">Correct</label>
<button class="form-control btn btn-primary" ng-click = "save()">Save</button>
<pre  ng-bind="dataShow"></pre>

Script:

var app = angular.module('qApp', []);
app.controller('qCtrl', function($scope) {
    var set = [];
    var op1 = [];
    $scope.save = function (){
        if($scope.correct1!==true){$scope.correct1=false;}      
        op1.push($scope.op1, $scope.correct1);
        var qus = [$scope.qus, op1];
        set.push(qus);
        $scope.dataShow = JSON.stringify(set); 
    };

});

Outputs:

After using JSON.stringify for the first entry the output looks like this:

[
 ["q1",["o1",false]]
]

and the output for the second entry is:

[
 ["q1", ["o1",false,"o2",true]], 
 ["q2", ["o1",false,"o2",true]]
] 

But I wanted something like this:

[
 ["q1", ["o1",false,]], 
 ["q2", ["o2",true]]
]

How to do that? true/false is the value of a check box.

2
  • can you provide plunkr or jsfiddle? Commented Sep 7, 2015 at 11:02
  • 1
    initialize op1 inside save method Commented Sep 7, 2015 at 11:09

2 Answers 2

3

@Nagesh Sanika is correct. Each question will have a list of options. So you can create the options array every-time when a new question is added to the set.

var app = angular.module('qApp', []);
app.controller('qCtrl', function($scope) {
    var set = [];

    $scope.save = function (){
        var op1 = [];  // Moved it inside the save method
        if($scope.correct1!==true){$scope.correct1=false;}      
        op1.push($scope.op1, $scope.correct1);
        var qus = [$scope.qus, op1];
        set.push(qus);
        $scope.dataShow = JSON.stringify(set); 
    };

});

Here is the plunker.

Sign up to request clarification or add additional context in comments.

2 Comments

you can do directly var op1 = [$scope.op1, $scope.correct1]; :-)
@Grundy, That's correct for the given scenario. But if multiple options are to be entered, we need to add then using push method.
1

To get your result, you need to empty the op1 array each time.

var app = angular.module('qApp', []);
app.controller('qCtrl', function($scope) {
var set = [];
var op1 = [];
$scope.save = function (){
    if($scope.correct1!==true){
      $scope.correct1=false;
    }      

    op1.push($scope.op1, $scope.correct1);

    var qus = [$scope.qus, op1];

    set.push(qus);
    op1=[];
    $scope.dataShow = JSON.stringify(set); 
 };
});

Hope this works :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.