ng-change事件第一次不起作用,选择切换按钮取消选择

时间:2015-12-26 05:17:49

标签: angularjs ionic-framework

我使用切换按钮来选择多个记录。我已选择显示现有记录,在第一次单击切换按钮取消选中时,在这种情况下ng-change事件不起作用。第二次点击相同的切换按钮进行选择,ng-change工作正常...

var unitsLists = [{Id:1, UnitType:'Kg'}...];
var selectedUnits = [1,2,...]; //existing unit ids array

请建议我解决这个问题...

<ion-list>
<ion-toggle ng-repeat="item in unitsLists" ng-checked="selectedUnits.indexOf(item.Id) != -1" ng-true-value="{{item.Id}}" ng-false-value="false" ng-model="UnitListModel[item.Id+item.UnitType]" ng-change="setToggleValue(UnitListModel[item.Id+item.UnitType], item.Id);" toggle-class="toggle-balanced">
                <h2>{{item.UnitType}}</h2>
            </ion-toggle>
            <a ng-hide="unitsLists.length > 0" class="item item-icon-right clsCenter">Record not found.</a>
        </ion-list>

1 个答案:

答案 0 :(得分:0)

好吧,我已经从你的代码及其工作中改变了很多!但是希望这会对你有帮助..!试试

控制器中的

 $scope.unitsLists = [{Id:1, UnitType:'unit1'},
  {Id:2, UnitType:'unit2'},
  {Id:3, UnitType:'unit3'},
  {Id:4, UnitType:'unit4'},
  {Id:5, UnitType:'unit5'}];

$scope.selectedUnits = [1,3]; //existing unit ids array

$scope.UnitListModel = {};
angular.forEach($scope.selectedUnits, function(value, key) {
  $scope.UnitListModel[value] = 'true';
});
$scope.setToggleValue = function (id) {
  var index = $scope.selectedUnits.indexOf(id);
  if ( index === -1) {
    $scope.selectedUnits.push(id);
    $scope.UnitListModel[id] = 'true';
  } else if (index != -1) {
    $scope.selectedUnits.splice(index, 1);
    $scope.UnitListModel[id] = 'false';
  }
  console.log("$scope.selectedUnits :"+JSON.stringify($scope.selectedUnits));
  console.log("$scope.UnitListModel :"+JSON.stringify($scope.UnitListModel));
}

html:

<ion-toggle ng-repeat="item in unitsLists"
                ng-checked="selectedUnits.indexOf(item.Id) != -1"
                ng-model="UnitListModel[item.Id]"
                ng-click="setToggleValue(item.Id);"
                toggle-class="toggle-balanced">
     <h2>{{item.UnitType}}</h2>
</ion-toggle>

你可以添加ng-true-value="{{item.Id}}" ng-false-value="false"