Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I am trying to display the questions based on the json response. Here is my code snippet:

function BackgroundInfoController($scope, $http, $location, profileInfo) {
    $scope.master = {};
    $scope.questions = {};
    $scope.backgroundInfo = profileInfo.backgroundInfo;
    $http.get("/ERegII-1.0/public/test/", { cache: true })
    .success(function(data) {
        /*alert(JSON.stringify(data));*/
    $scope.questions = data;
    }).error(function(data) {
        alert("fail:" + JSON.stringify(data));
        // TODO display error messages.
    });

Now I am trying to display the data on the page using angular controller, something like this:

<div data-ng-controller="BackgroundInfoController">
    <ol>
    <li data-ng-repeat="question in questions"> {{question.displayText}}<br> 
    {{question.responseType}} 
    </li>
    <div reponse-type="question.responseType" ref-data="question.demographicResponses">

    </div>
</ol>

    </div>

The json data that I am getting is in following format:

 [
     {
          "seqNo":0,
          "qstnNo":34,
          "responseType":"F",
          "responseRequired":false,
          "displayText":"If you have been provided with a state ID enter it here",
          "demographicResponses":[

          ],
          "dependentQuestionVO":[

          ],
          "selectedResponseIds":[

          ],
          "freeFormAnswer":null,
          "response":"",
          "independent":true,
          "answered":false,
          "triggered":false
       },
       {
          "seqNo":2,
          "qstnNo":2,
          "responseType":"R",
          "responseRequired":true,
          "displayText":"What is your ethnicity?",
          "demographicResponses":[
             {
                "possibleResponse":"Non-Hispanic",
                "seqNo":2,
                "respNo":201
             },
             {
                "possibleResponse":"Hispanic",
                "seqNo":2,
                "respNo":202
             },
             {
                "possibleResponse":"I prefer not to respond",
                "seqNo":2,
                "respNo":203
             }
    ]

 "dependentQuestionVO":[
         {
            "dependentQstnNo":3,
            "triggerRespNo":202,
            "triggerArrayElement":"[202,3]"
         }
      ],
      "selectedResponseIds":[
         "201",
         "202",
         "203"
      ],
      "freeFormAnswer":null,
      "response":"Non-Hispanic
Hispanic
I prefer not to respond
",
      "independent":false,
      "answered":true,
      "triggered":true
   },
   {
      "seqNo":3,
      "qstnNo":3,
      "responseType":"R",
      "responseRequired":true,
      "displayText":"What is your Hispanic origin?",
      "demographicResponses":[
         {
            "possibleResponse":"Mexican, Mexican, or Chicano",
            "seqNo":3,
            "respNo":301
         },
         {
            "possibleResponse":"Puerto Rican or Puerto Rican American",
            "seqNo":3,
            "respNo":302
         },
         {
            "possibleResponse":"Cuban or Cuban American",
            "seqNo":3,
            "respNo":303
         },
         {
            "possibleResponse":"Other",
            "seqNo":3,
            "respNo":304
         }
      ],
      "dependentQuestionVO":[

      ],
      "selectedResponseIds":[
         "301",
         "302",
         "303",
         "304"
      ],
      "freeFormAnswer":null,
      "response":"Mexican, Mexican, or Chicano
Puerto Rican or Puerto Rican American
Cuban or Cuban American
Other
",
      "independent":true,
      "answered":true,
      "triggered":false
   },
   {
      "seqNo":4,
      "qstnNo":4,
      "responseType":"M",
      "responseRequired":true,
      "displayText":"What is your race? Select all that apply.",
      "demographicResponses":[
         {
            "possibleResponse":"American Indian or Alaskan Native",
            "seqNo":4,
            "respNo":401
         },
         {
            "possibleResponse":"Asian",
            "seqNo":4,
            "respNo":402
         },
         {
            "possibleResponse":"Black or African American",
            "seqNo":4,
            "respNo":403
         },
         {
            "possibleResponse":"Native Hawaiian or Other Pacific Islander",
            "seqNo":4,
            "respNo":404
         },
         {
            "possibleResponse":"White",
            "seqNo":4,
            "respNo":405
         },
         {
            "possibleResponse":"Other",
            "seqNo":4,
            "respNo":406
         },
         {
            "possibleResponse":"I prefer not to respond",
            "seqNo":4,
            "respNo":407
         }
      ],
      "dependentQuestionVO":[

      ],
      "selectedResponseIds":[
         "401",
         "402",
         "403",
         "404",
         "405",
         "406",
         "407"
      ],
      "freeFormAnswer":null,
      "response":"American Indian or Alaskan Native
Asian
Black or African American
Native Hawaiian or Other Pacific Islander
White
Other
I prefer not to respond
",
      "independent":true,
      "answered":true,
      "triggered":false
   },
   {
      "seqNo":5,
      "qstnNo":5,
      "responseType":"R",
      "responseRequired":true,
      "displayText":"Do you communicate better (or as well) in English than in any other language?",
      "demographicResponses":[
         {
            "possibleResponse":"Yes",
            "seqNo":5,
            "respNo":501
         },
         {
            "possibleResponse":"No",
            "seqNo":5,
            "respNo":502
         }
      ],
      "dependentQuestionVO":[

      ],
      "selectedResponseIds":[
         "501",
         "502"
      ],
      "freeFormAnswer":null,
      "response":"Yes
No
",
      "independent":true,
      "answered":true,
      "triggered":false
   },
   {
      "seqNo":6,
      "qstnNo":6,
      "responseType":"R",
      "responseRequired":false,
      "displayText":"Which of the following best describes your current employment status?",
      "demographicResponses":[
         {
            "possibleResponse":"Employed part-time (29 or fewer hours per week)",
            "seqNo":6,
            "respNo":601
         },
         {
            "possibleResponse":"Employed full-time",
            "seqNo":6,
            "respNo":602
         },
         {
            "possibleResponse":"Unemployed (seeking employment)",
            "seqNo":6,
            "respNo":603
         },
         {
            "possibleResponse":"Not in the labor force (homemaker, family caregiver, student, retired )",
            "seqNo":6,
            "respNo":604
         }
      ],
      "dependentQuestionVO":[

      ],
      "selectedResponseIds":[
         "601",
         "602",
         "603",
         "604"
      ],
      "freeFormAnswer":null,
      "response":"Employed part-time (29 or fewer hours per week)
Employed full-time
Unemployed (seeking employment)
Not in the labor force (homemaker, family caregiver, student, retired )
",
      "independent":true,
      "answered":true,
      "triggered":false
   },
   {
      "seqNo":7,
      "qstnNo":7,
      "responseType":"S",
      "responseRequired":false,
      "displayText":"What was the last grade of school that you completed?",
      "demographicResponses":[
         {
            "possibleResponse":"5th grade or lower",
            "seqNo":7,
            "respNo":701
         },
         {
            "possibleResponse":"6th grade",
            "seqNo":7,
            "respNo":702
         },
         {
            "possibleResponse":"7th grade",
            "seqNo":7,
            "respNo":703
         },
         {
            "possibleResponse":"8th grade",
            "seqNo":7,
            "respNo":704
         },
         {
            "possibleResponse":"9th grade (high school freshman)",
            "seqNo":7,
            "respNo":705
         },
         {
            "possibleResponse":"10th grade (high school sophomore)",
            "seqNo":7,
            "respNo":706
         },
         {
            "possibleResponse":"11th grade (high school junior)",
            "seqNo":7,
            "respNo":707
         },
         {
            "possibleResponse":"12th grade (high school senior)",
            "seqNo":7,
            "respNo":708
         }
      ],

Some questions are based on a specific answer for a question. Can someone help me to display these questions answers in agyularjs? F=free form text, M= multiselect form (checkbox) and R= radio button.

share|improve this question
1  
A straightforward approach would be to use ng-if or ng-switch to chose the template to generate the question with. But a few custom directives might be nicer. –  towr Jan 8 '14 at 19:07

2 Answers 2

This probably doesn't do exactly what you want, but it should provide a possible starting point.

<div ng-app="myapp">
    <ol ng-controller="ctrl">
        <li data-ng-repeat="question in questions"> 
          <div ng-switch on="question.responseType">
            <div ng-switch-when="F" textquestion="question"></div>
            <div ng-switch-when="R" radioquestion="question"></div>
            <div ng-switch-when="M" multiquestion="question"></div>
            <div ng-switch-when="S" selectquestion="question"></div>
          </div>
        </li>
    </ol>
</div>

The templates in these directives are a bit long, so it might be better to split them off as separate template and use templateUrl to get them. (And if you're never going to reuse them, you could just insert the templates in the html above.)

app.directive("textquestion", function(){
    return {
        restrict: 'A',
        template : '<label>{{question.displayText}}<br/><input name="{{question.qstnNo}}" type="text"/></label>',
        scope : { question: '=textquestion' }
    };
})
.directive("radioquestion", function(){
    return {
        restrict: 'A',
        template : '{{question.displayText}}<br/><label ng-repeat="resp in question.demographicResponses"><input  name="{{question.qstnNo}}" type="radio" value="{{resp.respNo}}" /> {{resp.possibleResponse}} </label> ',
        scope : { question: '=radioquestion' }
    };
})
.directive("multiquestion", function(){
    return {
        restrict: 'A',
        template : '{{question.displayText}}<br/><label ng-repeat="resp in question.demographicResponses"><input  name="{{question.qstnNo}}" type="checkbox" value="{{resp.respNo}}" /> {{resp.possibleResponse}} </label>',
        scope : { question: '=multiquestion' }
    };
})
.directive("selectquestion", function(){
    return {
        restrict: 'A',
        template : '{{question.displayText}}<br/><label> <select name="{{question.qstnNo}}"><option ng-repeat="resp in question.demographicResponses" value="{{resp.respNo}}"> {{resp.possibleResponse}}</option></select></label>',
        scope : { question: '=selectquestion' }
    };
})

http://jsfiddle.net/gwt3Q/

share|improve this answer
    
This is very neat! Thank you for your help Towr. –  Irfan Ali Jan 10 '14 at 20:07
    
Towr- do you have any idea how can I add a class to the display text based on responseRequired == 'true' –  Irfan Ali Feb 26 '14 at 21:52
    
@IrfanAli You can use ng-class, e.g. <ANY ng-class="{someclass : question.responseRequired == 'true' }" > –  towr Feb 27 '14 at 7:03
    
well.. I actually tried this like <labe ng-class="{required: question.responseRequired = = 'true'}"> but somehow its not working! –  Irfan Ali Feb 27 '14 at 15:03
    
Ok I got it! Here how it works: <ANY ng-class="{true: 'classname'} [question.responseRequired == true]"> –  Irfan Ali Feb 27 '14 at 15:43

Thank you Towr! I guess its a good way to manipulate teh JSON. However, I have used different approach.

Here is my approach which works fine as of now :)

 <li ng-repeat="question in questions"><strong>{{question.displayText}}</strong><br> 
        <input type="text" ng-show="question.responseType == 'F'" name="questions.seqNo"  ng-model="answers[question.seqNo]" />

        <span ng-show="question.responseType == 'R'" data-ng-repeat=" demoResponse in question.demographicResponses">
        <input type="radio" ng-show="question.responseType == 'R'" name="{{questions.seqNo}}"  ng-model="answers[question.seqNo]" value="{{ demoResponse.respNo }}" /> {{demoResponse.possibleResponse}} <br>
        </span>
         <span ng-show="question.responseType == 'M'" data-ng-repeat=" demoResponse in question.demographicResponses">
        <input type="checkbox" ng-show="question.responseType == 'M'" name="M" ng-checked="answers[question.seqNo].indexOf(demoResponse.respNo) > -1" ng-click="toggleSelection(question.seqNo, demoResponse.respNo)"  /> {{demoResponse.possibleResponse}} <br>
        </span>

        <span ng-show="question.responseType == 'S'">
            <select data-ng-model="answers[question.seqNo]" >
                <option ng-repeat="demoResponse in question.demographicResponses" value="{{demoResponse.respNo}}">{{demoResponse.possibleResponse}}</option>
            </select>
         </span> 

    </li>

My Script code is here. I have also bind the data to the scope:

function BackgroundInfoController($scope, $http, $location, profileInfo) {
    $scope.master = {};
    $scope.questions = {};
    $scope.answers = {};
    $scope.backgroundInfo = profileInfo.backgroundInfo;
    $http.get("/ERegII-1.0/public/test/", { cache: true })
    .success(function(data) {
    /*  alert(JSON.stringify(data));*/
        $scope.questions = data;
        }).error(function(data) {
        alert("fail:" + JSON.stringify(data));
        // TODO display error messages.
    });


    $scope.toggleSelection = function toggleSelection(seqNo, option) {
        if ($scope.answers[seqNo] == null) {
            $scope.answers[seqNo] = [];
        }
        var index = $scope.answers[seqNo].indexOf(option);
        if (index > -1) {
            $scope.answers[seqNo].splice(index, 1);
        } else {
            $scope.answers[seqNo].push(option);
        }
    //  alert($scope.answers[seqNo]);
    };
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.