使用angularjs操作JSON数据

时间:2014-01-08 18:56:00

标签: json angularjs

我正在尝试根据json响应显示问题。这是我的代码片段:

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

现在我尝试使用角度控制器在页面上显示数据,如下所示:

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

我得到的json数据采用以下格式:

 [
     {
          "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
         }
      ],

有些问题是基于问题的具体答案。有人可以帮我在agyularjs中显示这些问题的答案吗? F =自由格式文本,M =多选格式(复选框)和R =单选按钮。

2 个答案:

答案 0 :(得分:0)

这可能不是你想要的,但它应该提供一个可能的起点。

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

这些指令中的模板有点长,因此最好将它们作为单独的模板拆分,并使用templateUrl来获取它们。 (如果你永远不会重复使用它们,你可以在上面的html中插入模板。)

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/

答案 1 :(得分:0)

谢谢你!我想这是操纵JSON的好方法。但是,我使用了不同的方法。

这是我的方法,目前工作正常:)

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

我的脚本代码在这里。我还将数据绑定到范围:

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