How do I bind to list of checkbox values with AngularJS?

前端 未结 29 2331
天涯浪人
天涯浪人 2020-11-22 05:20

I have a few checkboxes:





        
29条回答
  •  遥遥无期
    2020-11-22 06:04

    I have adapted Yoshi's accepted answer to deal with complex objects (instead of strings).

    HTML

    {{permission.name}}


    allPermissions: | {{permission.name}} |

    selectedPermissions: | {{permission.name}} |

    JavaScript

    Array.prototype.indexOfObjectWithProperty = function(propertyName, propertyValue)
    {
        for (var i = 0, len = this.length; i < len; i++) {
            if (this[i][propertyName] === propertyValue) return i;
        }
    
        return -1;
    };
    
    
    Array.prototype.containsObjectWithProperty = function(propertyName, propertyValue)
    {
        return this.indexOfObjectWithProperty(propertyName, propertyValue) != -1;
    };
    
    
    function TestController($scope)
    {
        $scope.allPermissions = [
        { "id" : 1, "name" : "ROLE_USER" },
        { "id" : 2, "name" : "ROLE_ADMIN" },
        { "id" : 3, "name" : "ROLE_READ" },
        { "id" : 4, "name" : "ROLE_WRITE" } ];
    
        $scope.selectedPermissions = [
        { "id" : 1, "name" : "ROLE_USER" },
        { "id" : 3, "name" : "ROLE_READ" } ];
    
        $scope.toggleSelection = function toggleSelection(permission) {
            var index = $scope.selectedPermissions.indexOfObjectWithProperty('id', permission.id);
    
            if (index > -1) {
                $scope.selectedPermissions.splice(index, 1);
            } else {
                $scope.selectedPermissions.push(permission);
            }
        };
    }
    

    Working example: http://jsfiddle.net/tCU8v/

提交回复
热议问题