【问题标题】:Angular ng-repeat with bootstrap input checkbox with dynamic ng-model using ng-true-valueAngular ng-repeat 与 bootstrap 输入复选框与动态 ng-model 使用 ng-true-value
【发布时间】:2015-07-26 19:32:23
【问题描述】:

这个问题对我来说有点难以解释,所以我会尽力而为。我正在尝试使用动态 ng-model 正确地使用 ng-true-value 成功实现 Angular 复选框。

<div ng-app="myApp">
<div ng-controller="MyCtrl">
    <div ng-repeat="asset in asset">
         <h5>{{ asset.title }} categories are...{{ asset.category[0] + " and " + asset.category[1] }}</h5>

        <div class="form-group">
            <label>Business</label>
            <div class="checkbox" ng-repeat="category in categoryFactory.business">
                <input type="checkbox" id="{{category}}" ng-true-value="{{'category'}}" ng-model="asset.category[$index]">
                <label for="{{category}}">{{category}}</label>
            </div>
        </div>
        <div class="form-group">
            <label>Personal</label>
            <div class="checkbox" ng-repeat="category in categoryFactory.personal">
                <input type="checkbox" id="{{category}}" ng-true-value="{{'category'}}" ng-model="asset.category[$index]">
                <label for="{{category}}">{{category}}</label>
            </div>
        </div>
    </div>
</div>

我的最终目标是当我加载我的资产(在下面找到...)时,它会像My end goal 的图片一样显示,并选中正确的复选框。商业和个人类别来自工厂,每个表单组复选框来自工厂的商业/个人中的 ng-repeat 列表。

$scope.asset = [{
  title: "Sales Agreement",
  category: ["finance-admin", "running-a-business"]
}];

我的问题是必须在复选框内正确实现 ng-model。由于每个资产可以有 1 个或多个类别,因此它需要是动态的。我尝试使用 $index 使我的 ng-model 动态化...

ng-model="asset.category[$index]"

但这似乎不像我希望的那样有效。我可能错过了一些非常简单的东西,我们将不胜感激。

谢谢! 顺便说一句,这里是 JSFIDDLE

【问题讨论】:

  • ??
  • 不确定您到底对什么感到困惑。 ng-true-value 来自这个 ng-repeat="category in categoryFactory.business"。 Ng-model 我正在尝试根据资产类别进行动态化,在这种情况下是类别:[“finance-admin”,“running-a-business”]
  • 在您的 ng-true-value="{{'category'}}" 中都有一个单引号,只是想指出以防万一。

标签: javascript angularjs twitter-bootstrap checkbox


【解决方案1】:

目前根据您的 $index 逻辑,两个数组 categoryFactory.businessasset.category 必须具有相同的大小,所以这里是更新后的 jsfiddle

但主要是这个

首先,对于您的情况,ng-true-value 应该是一个表达式

ng-true-value="{{category}}"

其次,您的 asset.category 数组索引应该与您在 categoryFactory.business 数组中的选项匹配

$scope.asset = [{
    title: "Sales Agreement",
    category: ["", "running-a-business","",  "","finance-admin"]
}];

可能有更好的选择来管理这个而不依赖于 $index 但这应该适合你的情况

【讨论】:

    【解决方案2】:

    我使用了ng-checked,你可以把function作为一个属性值,ng-repeat会在每个循环中对函数求值。

    <input type="checkbox" id="{{category}}" ng-checked="isCategory(category)" >
    
    $scope.isCategory = function(category){
       return  $scope.asset[0].category.indexOf(category) >= 0;
    }
    

    在 isCategory() 中,我们正在检查asset.category 数组中类别的索引,如果找到它就会为真。

    https://jsfiddle.net/pg5dqgr9/8/

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签