打开其他按钮时自动关闭切换按钮

时间:2016-07-28 18:48:41

标签: javascript html angularjs ionic-framework

我有嵌套的切换按钮,默认情况下是关闭的,当它在它上面时会将值保存到localstorage。我想要做的是当一个人打开并且你试图打开另一个时,第一个应该自动关闭而另一个打开

.controller('shops',['$scope','$http','$timeout',function($scope,$http,$timeout){
$http.get('http://localhost/moves/templates/shopping.php').success(function(data){
       $scope.shops=data ;
        });

 $scope.pushNotification = {};
  $scope.pushNotification.text = "Sample"
  $scope.pushNotification.checked = false;

  $scope.pushNotificationChange = function(item) {
    console.log('Push Notification Change',    $scope.pushNotification.checked);
        if($scope.pushNotification.checked){
            localStorage.setItem("shop_id",($scope.item.shop_id));
        }else{
             localStorage.removeItem("shop_id");
         }
  };


  //$scope.pushNotification = { checked: false };

}])

HTML

<div ng-controller="shops" ng-repeat="item in shops">
          <ion-item class="item-thumbnail-left item-text-wrap"> 
          <img src="img/index/fashion.png" alt="photo" width="32" height="32" />
          <h2>{{item.shop_name}} </h2>
          <p>{{item.biz_location}}</p>

    <input type="hidden" value="{{item.shop_id}}">

          <div align="right">
          <label class="toggle toggle-balanced">
          <input type="checkbox"ng-model="pushNotification.checked"
                    ng-change="pushNotificationChange()">
          <div class="track"><div class="handle"></div></div> 
          </label>
          </div>
          </ion-item>
          </div>

1 个答案:

答案 0 :(得分:0)

您可能希望每个项目都有自己的ng-model与每个特定项目绑定,而不是为所有复选框设置一个ng-model复选框。这样,当一个人更改并点击范围上的单个更改方法时,您可以根据需要更新每个项目的复选框模型(在这种情况下,将选中状态设置为false)。

这是一个工作示例,简化了OP中的现有代码:

angular.module('App', [])
.controller('Shops',['$scope','$http','$timeout',function($scope,$http,$timeout){

  $scope.shops = [
    {
      shop_id: 1,
      shop_name: 'Shop One',
      checked: false,
    },
    {
      shop_id: 2,
      shop_name: 'Shop Two',
      checked: false,
    },
    {
      shop_id: 3,
      shop_name: 'Shop Three',
      checked: false,
    }
  ];

  $scope.onItemChange = function(item) {
    // Loop over all our shops and set other checked properties to false if not our current item
    angular.forEach($scope.shops, function(shop) {
      if (shop !== item) {
        shop.checked = false;
      }
    });
    // Do whatever else when an item changes
  };
}]);
<body ng-app="App">
  <div ng-controller="Shops">
    <div ng-repeat="item in shops">
      <!-- Each checkbox is using a specific model for each item -->
      <input type="checkbox" ng-model="item.checked" ng-change="onItemChange(item)"> 
      <span>{{item.shop_name}}</span> 
    </div>
  </div>
  
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</body>