2016-01-31 16 views
0

我有一堆單選按鈕作爲選項的問題。每個問題都有一個部分,每當我從一個部分移動到另一個時,我會失去除最近一個之外的按鈕的價值。我該如何解決?AngularJS:移動到下一個部分後,單選按鈕丟失了值

部分:

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

您需要使用服務來存儲數據。每個路由更改意味着您的控制器的新實例,並且所有作用域都被銷燬 – charlietfl

+0

什麼是'whichItem'和'currItem'?意味着它的定義在哪裏?可以請稍微清楚一下你在商店功能上做什麼? –

+0

對不起,沒有這樣的東西,哪個項目。 whichItem == currItem – QuikProBroNa

回答

0

爲了設置一個值,無線輸入您需要添加NG-模式

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

每次當前rou te(在相同的層級中)被改變,然後前一個控制器被銷燬並且下一個控制器被創建,因此該值之間沒有保存。您可以使用服務,但也可以將值存儲在$ rootScope而不是$範圍,因爲它適用於所有應用程序,所以您可以在轉換之間獲得共享數據。只需注入$ rootScope到您的控制器並使用它:$ rootScope.anyValue = val;

+0

'rootScope'的值在轉換時也會丟失 – QuikProBroNa

+0

取決於您如何使用它,發佈完整的代碼並且我將能夠查看它 – innovarerz

相關問題