使用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>

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

阅读 2.9k
2 个回答

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

  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);
    }
}

既然用了angular,为什么还要用jquery的思路去写代码呢
在input上绑上ng-model可以监听选中状态,然后通过model比对去控制另一个input的选中与否
通过数据去控制UI渲染,这是ng这类框架的理念

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进