【问题标题】:AngularJS display element if it's in the arrayAngularJS 显示元素(如果它在数组中)
【发布时间】:2014-06-19 11:56:05
【问题描述】:

我正在尝试根据之前选择的用户权限重新填充一组复选框。

我创建了一个权限 id 数组,并希望将输入元素与 id 数组进行比较,如果匹配,则将复选框显示为选中,否则显示未选中的复选框。

这就是我创建$scope.assigned 数组的方式:

$scope.user.$promise.then(function(result) {
    $scope.user = result;
    $scope.assigned = [];
    angular.forEach($scope.user.permissions, function(value, key) {
        this.push(value.id);
    }, $scope.assigned);

console.log($scope.assigned);

$scope.assigned 被记录到控制台时,我留下了一个数组,例如["2", "3", "4"],代表先前选择的权限ID。现在我想将它们与permissions.id进行比较

观点:

<h4>Manage Permissions</h4>
<div class="form-group" ng-repeat="permission in permissions">
    <label>
        <input ng-if="permission.id == assigned" type="checkbox" ng-checked="true" checklist-model="user.permissions" checklist-value="permission.id" class="checkbox-inline">
        {{ permission.display_name }}
    </label>
</div>
<button class="btn btn-success" type="submit">Save</button>

我认为我可以做类似ng-if="permission.id == assigned" 的事情,但这不起作用。我需要一种方法来检查permission.id 是否与assigned 中的任何内容匹配。

我以前在 PHP 中这样做过:if(in_array($permission['id'], $assigned))

如何在 AngularJS 中实现这一点?感谢您的任何建议。

【问题讨论】:

    标签: javascript php arrays angularjs checkbox


    【解决方案1】:

    使用indexOf:

    ng-if="assigned.indexOf(permission.id) != -1"
    

    【讨论】:

    • 太棒了,谢谢@merlin!不知道 indexOf(),我对 JavaScript 和 AngularJS 还是很陌生。感谢您的帮助!
    • @MitchGlenn 如果你想支持旧浏览器,也可以看看compatibility table of Array.prototype.indexOf
    猜你喜欢
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2015-07-20
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    相关资源
    最近更新 更多