AngularJS:单选按钮在移动到下一个部分后失去价值

AngularJS: Radio buttons lost value after moving to next partial

本文关键字:失去 下一个部 单选按钮 移动 AngularJS      更新时间:2023-09-26

我有一堆问题,将单选按钮作为选项。每个问题都有一个部分,每当我从一个部分移动到另一个部分时,除了最近的一个之外,我都会丢失按钮的值。我该如何解决这个问题?

部分:

<link rel="stylesheet" href="css/common.css" />
<section class="myinfo">
   <center>
      <a href="#details/{{prevItem}}" class="button">PREV</a>
      <a href="#details/{{nextItem}}" class="button">NEXT</a>
   </center>
   <p class="sel">
       {{questions[currItem].q}}
   </p>
   <ul>
       <li class="optlist" ng-repeat="item in questions[currItem].opt">
           <label class="formgroup">
              <input type="radio" name="q" ng-click="store(item.pos, currItem)" value="{{item.pos}}" />
              <span>{{item.val}}</span>
           </label>
       </li>
   </ul>
   <p class="ques">You've chosen: {{selopt}}</p>
   <center>
      <a ng-click="show()">Check</a>
   </center>
</section>

控制器:

myApp.controller('OneController', ['$scope', '$http','$routeParams' ,function($scope, $http, $routeParams) {
  $http.get('js/JOSCO.json').success(function(data) {
    $scope.questions = data;
    $scope.currItem= $routeParams.itemId;
    $scope.parseInt = parseInt;
    if ($routeParams.itemId > 0) {
        $scope.prevItem = Number($routeParams.itemId) - 1;
    }
    else {
        $scope.prevItem = $scope.questions.length - 1;
    }
    if ($routeParams.itemId < $scope.questions.length-1) {
        $scope.nextItem = Number($routeParams.itemId) + 1;
    }
    else {
        $scope.nextItem = 0;
    }
  });
  $scope.ansArr = [];
  $scope.store = function(pos, index) {
    $scope.ansArr[index] = pos;
    alert($scope.ansArr[index]);
  };
  $scope.show = function() {
    $scope.s = "";
    for (var i = 0; i < 12; i++) {
      $scope.s = $scope.s + "  " + $scope.ansArr[i];
    }
    alert($scope.s); // returns undefined for everything except the last one
  };
}]);

为了设置无线电输入的值,您需要添加 ng-model

<input type="radio" data-ng-model="item.pos"/>

每次更改当前路由(在同一层次结构中(时,都会销毁上一个控制器并创建下一个控制器,因此不会在两者之间保存该值。您可以如上所述使用服务,但您也可以将值存储在$rootScope而不是$scope中,因为它对所有应用程序都是通用的,因此您可以在转换之间获得共享数据。只需将$rootScope注入控制器并使用它:$rootScope.anyValue = val;