jquery - 使用attr时,checklist-model不能将勾选的对象写入checklist-model

查看:79
本文介绍了jquery - 使用attr时,checklist-model不能将勾选的对象写入checklist-model的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

项目需要展示复选框列表,选中复选框列表A中的某一项,自动勾选复选框列表B中的对应项。目前使用checklist-model组件,当勾选某一项时,将值存到selectedLists。现在勾选是可以实现了,不过当自动勾选B中的项目时,没有将选中的值写到selectedLists中。

现在把代码贴出来,欢迎探讨

html代码

<div class='panel-body' id='aList'>
    <div ng-repeat='aList in aLists'>
        <input type="checkbox" ng-click='show($event,aList.id)'>{{aList.name}}
    </div>
</div>
<div class='panel-body' id='bList'>
    <div ng-repeat='bList in bLists track by $index'>
        <input type="checkbox" checklist-model='selectedLists' checklist-value='bList' 
               data-parent-id='{{bList.id}}'>
        {{bList.name}}
    </div>
</div>

js代码

<script type="text/javascript">
    $scope.selectedLists= [];
    
    $scope.show = function(event,id){
    var checkBox = $(event.target);
    var cValue = id;
    var isCheck = checkBox.prop('checked');
    $("#bList input").each(function(){
        if(cValue == $(this).data('stationId')){
            $(this).prop('checked',isCheck);//这里设置勾选状态
        }
    });
}
</script>

请问有什么问题,欢迎指正,谢谢大家。

解决方案

不知道你的具体需求是什么。按照你的描述看:

  1. 选中 A 的时候 B 也选中,反之亦然

  2. 动态更新 $scope.selectedLists

  3. 两个都是通过 ng-repeat 生成的

如果需求只是这些,那既不需要使用第三方组件,更不需要 jQuery。

链接:https://jsfiddle.net/S1ngS1ng...

核心逻辑:

  1. aLists 每一个元素中有两个属性,map 之后有三个,类似于:

    {name: 'foo', value: 'bar', selected: false}

    其中 name 表示要显示在页面上的,value 表示你要用来存储的,selected 是用来判断是否选中的

  2. bLists 每一个元素中只有一个 name 属性,负责显示内容

  3. B 中是否选中通过 A 中对应元素的 selected 属性去判断。既然你想把这两个动态绑定上,那我觉得这样做应该是最合适的

  4. 更新 $scope.selectedLists 的逻辑:

$scope.update = function(index) {
    // 找到 aLists 中的对应元素
    var _ref = $scope.aLists[index];

    if(_ref.selected) {
        if ($scope.selectedLists.indexOf(_ref.value) === -1) {
            // 如果选中元素的 value 值在 $scope.selectedLists 中不存在,则 push
            $scope.selectedLists.push(_ref.value);
        }
    } else {
        // 若 selected 为 false,就删除对应的值
        $scope.selectedLists.splice($scope.selectedLists.indexOf(_ref.value), 1);
    }
}

这篇关于jquery - 使用attr时,checklist-model不能将勾选的对象写入checklist-model的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆