如何在更改视图时保持用户选择的选项

时间:2016-07-04 10:53:07

标签: angularjs drop-down-menu angularjs-select

Demo:

我有一个下拉列表,选项正在从JSON中删除。 说

<body ng-app="staticSelect">
  <div ng-controller="ddController">
  <form name="myForm">
    <label for="singleSelect"> Single select: </label><br>
    <select name="singleSelect" ng-model="data.singleSelect">
      <option ng-repeat="x in options">{{x}}</option>
    </select><br>
    <tt>singleSelect = {{data.singleSelect}}</tt>
  </form>
</div>
</body>

我有两个视图page1.html和page2.html

在page1.html中的

我有以下代码。 当用户选择一个选项时,选择具有上述选项的框说,用户已选择三个。这必须保存在某个地方。我不在哪里保存,所以接下来当用户点击page2.html时,在page1.html之前选择的数据不应该重置。

HTML:

app.controller('ddController', ['$scope', function($scope) {
    $scope.data = {
     singleSelect: null,
    };
    $scope.options = ["red","blue","yellow"];
 }]);

 app.config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: '01.html',
        controller: 'htmlCtrl',
      })
      .when('/html', {
        templateUrl: '02.html',
        controller: 'htmlCtrl',
      })
 })

JS

   .pagination-box ul{
    	display: flex;
        justify-content: space-between;
    }
    
    .pagination-box ul li{
    	list-style: none;
    	text-align: center;
    	display: inline-block;
    }
    
    .pagination-box ul li:not(:first-child):not(:last-child){
    	
    	border :1px solid #cfcfcf;
    	border-radius: 50%;
    	width: 40px;
    	height: 40px;
    	padding: 9px;
    
    }
    
    .pagination-box ul li.active{
    	border:2px solid #ff9805;
    }

任何帮助将不胜感激! 谢谢

1 个答案:

答案 0 :(得分:1)

在主视图中添加了“ng-cookies”的引用,以及用于设置和获取cookie的服务。

在Html中:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-cookies.js"></script>

绑定html具有通过ng-change

设置cookie的方法
<select name="singleSelect" ng-model="data.singleSelect" ng-change="setSelect()">
   <option ng-repeat="x in options">{{x}}</option>
</select>

您可以在Working Demo

中看到CookieService

在控制器中:

setSelect()方法被触发时,所选值在cookie中设置,当视图返回到它时将重新存储cookie中的值

if(cookieService.getAppData("selected") !== null && cookieService.getAppData("selected") !== undefined){
 $scope.data.singleSelect = cookieService.getAppData("selected");
}

$scope.setSelect = function (){
   cookieService.setAppData("selected", $scope.data.singleSelect);
}