角度 - 存储复选框值并显示它们



假设你有 27 个复选框,我们称它们为"类别"。这些复选框位于一个部分中,您可以多次选择它们并保存。

问题是:如果您保存表单,类别将在MySQL中添加到您的个人资料中。

我的问题是:

  • 我应该如何命名模型,

  • 发送表单后我应该如何存储 de 值

有一个解决方案,我保存了第 n 个类别,然后在加载时单击它们,但这不是最好的。

这是代码:

 $scope.getSelectedCats = function()  //Returning array: [1,4,5,6]
 {
   $return_array = [];
   $i = 0;
   if($scope.whoareu.develop){ $return_array[$i] = 1; $i++;}
   if($scope.whoareu.design){ $return_array[$i] = 2; $i++;}
   if($scope.whoareu.produce){ $return_array[$i] = 3; $i++;}
   if($scope.whoareu.repair){ $return_array[$i] = 4; $i++;}
   [...]
   return $return_array;
 }

.HTML

  <p>
    <input ng-model="whoareu.develop" type="checkbox" value=1 id="WAY8" name="whoareu"  />
    <label for="WAY8">Develop</label>
  </p>
  <p>
    <input ng-model="whoareu.design" type="checkbox" value=2 id="WAY9" name="whoareu"  />
    <label for="WAY9">Design</label>
  </p>
  <p>
    <input ng-model="whoareu.produce" type="checkbox" value=3 id="WAY10" name="whoareu" />
    <label for="WAY10">Produce</label>
  </p>
  <p>
    <input ng-model="whoareu.repair" type="checkbox" value=4 id="WAY11" name="whoareu" />
    <label for="WAY11">Repair</label>
  </p>
  [...]

最后,一个非常丑陋的加载检查解决方案:

  <?php
  //$dbData = Data row from mysql, in object, by Wordpress
  echo "setTimeout(function(){";
  foreach(explode(',', $dbData->interested_in) as $val)
  {
    //echo "$('input:checkbox[name=whatareu]').filter('[value=$val]').click();";
    echo "$('input:checkbox[name=whatareu]').eq($val-1).click();";
  }
  echo "}, 1000);";
  ?>
我不知道

我是否很好地理解了你的问题,请参阅我的片段。如果需要,您可以创建一些映射函数setDefaultState(basedOn),用于在模型checkboxs中设置checked

如果问题是离开控制器后数据丢失,则应使用一些单例存储,例如Angular的工厂,并将选中的类别存储在那里。

angular.module('app', [])
.controller('FrameController', ['$injector',
  function($injector) {
    var vm = this;
    vm.checkboxs = [{
      id: 'WAY8',
      label: 'Develop',
      checked: true
    }, {
      id: 'WAY9',
      label: 'Design'
    }]
    angular.extend(vm, {
      save: save
    })
    function save() {
      // API call
      console.log('checked: ', vm.checkboxs.filter(function(c) {
        return c.checked
      }).map(function(c) {
        return {
          id: c.id
        }
      }));
    }
  }
]);
setTimeout(function() {
  angular.bootstrap(document.getElementById('body'), ['app']);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="body">
  <div ng-controller="FrameController as vm">
    <ul>
      <li ng-repeat="checkbox in vm.checkboxs">
        <input ng-model="checkbox.checked" type="checkbox" id="{{checkbox.id}}" name="whoareu" />
        <label for="{{checkbox.id}}">{{checkbox.label}}</label>
      </li>
    </ul>
    <button ng-click="vm.save()">
      Save
    </button>
  </div>
</div>

最新更新