【问题标题】:Checkbox List not being populated after formatting array as JSON and mapping in ng-repeat将数组格式化为 JSON 并在 ng-repeat 中映射后未填充复选框列表
【发布时间】:2016-02-24 14:50:15
【问题描述】:

plunk - https://plnkr.co/edit/2ptIAdOyaIw8mGqpU7Cp?p=preview

正在发生的事情的概要 - onload 执行函数 createObjectFromEntityArrayWithKeys(),它格式化值数组以添加两个新键,其中一个属于新值 boolean checked。新数组 $scope.newEntityArray$scope 上创建并在我的 ng-repeat 中访问。它被分配了新的格式化数据。

这源于一个较早的问题 - 保存 ng-repeat 复选框菜单的状态,同时/之后/已被过滤。

因为我正在处理一个只有值的数组,所以我必须更改它以将一个布尔值 checked 附加到每个值 - 给我留下一个 JSON 对象数组。这使我能够保存每个复选框的状态。问题是我认为我的映射不正确,或者我将 ng-repeat 与对象映射一起使用。我真的不确定为什么没有填充列表。任何帮助表示赞赏。

编辑

我也尝试过使用两个ng-repeats,但结果相同:

<div ng-repeat="entity in newEntityArray | filter:simpleFilter">
    <div ng-repeat="(val, checked) in entity">
        <label> <input
           style="display: inline-block; margin-top: 5px"
           type="checkbox" ng-model="checked"
           ng-change="setModalEntity(val,checked)" /> <a>{{val}}</a>
        </label>
    </div>
</div>

【问题讨论】:

    标签: javascript html angularjs json ng-repeat


    【解决方案1】:

    这个问题正是由使用 this onload 从全局范围调用函数引起的。您应该尝试这样的“角度方式”重构:

    控制器:

    var createObjectFromEntityArrayWithKeys = function(){
      $scope.newEntityArray = entityArray.map(function(value){
          return {"val":value, "checked":false};
      });
    };
    
    // execute when load the controller
    createObjectFromEntityArrayWithKeys();
    

    查看:

    我只删除了onload 属性。

    <body ng-app="app">
      <div ng-controller = "mainCtrl">
        <div>
          <input type="text" placeholder="Search" ng-model="simpleFilter">
        </div>
        <div ng-repeat="entity in newEntityArray | filter:simpleFilter">
          <label> <input
            style="display: inline-block; margin-top: 5px"
            type="checkbox" ng-model="entity.checked"
            ng-change="setModalEntity(entity.val,entity.checked)" /> <a>{{entity.val}}</a>
          </label>
        </div>
        {{entityFromSelection}}
      </div>
    </body>
    

    DEMO PLUNKER

    【讨论】:

      猜你喜欢
      • 2014-11-25
      • 2021-03-01
      • 2015-03-19
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多