如何使用firebase数据库和ng-repeat设置选择选项

时间:2016-07-27 12:00:42

标签: angularjs firebase firebase-realtime-database

数据库(.JSON):

{
  "permissionLevels" : {
    "Admin" : {
      "Comment Access" : "value",
      "Page Access" : "value",
      "Post Access" : "value"
    },
    "Default" : {
      "Comment Access" : "value",
      "Page Access" : "value",
      "Post Access" : "value"
    },
    "Template" : {
      "Comment Access" : "value",
      "Page Access" : "value",
      "Post Access" : "value"
    }
  },
  "users" : {
    "User 1" : {
      "Email" : "user1@gmail.com",
      "Name" : "User 1",
      "PhotoURL" : "https://lh5.googleusercontent.com/-m1_AWD2hhp0/AAAAAAAAAAI/AAAAAAAAAZY/IhIwoLVwl6U/s96-c/photo.jpg",
      "Role" : "Default",
      "uid" : "1235"
    },
    "User 2" : {
      "Email" : "user2@gmail.com",
      "Name" : "User 2",
      "Role" : "Default",
      "uid" : "1236"
    },
    "User 3" : {
      "Email" : "user3@gmail.com",
      "Name" : "User 3",
      "PhotoURL" : "https://lh5.googleusercontent.com/-m1_AWD2hhp0/AAAAAAAAAAI/AAAAAAAAAZY/IhIwoLVwl6U/s96-c/photo.jpg",
      "Role" : "Admin",
      "uid" : "1237"
    }
  }
}

HTML:

<table id="table">
  <tr>
    <th>Name</th>
    <th>Email</th>
    <th>Permission Level</th>
  </tr>
  <tr ng-repeat="(key, value) in users">
    <td>{{value.Name}}</td>
    <td>{{value.Email}}</td>
    <td>
      <select name="{{key}}">
        <option ng-model="key">{{value.Role}}</option>
        <option ng-repeat="(permissionLevel, permissions) in permissionLevels.permissionLevels" ng-if="permissionLevel!=value.Role && permissionLevel!='Template'" ng-selected="string">{{permissionLevel}}</option>
      </select>
    </td>
  </tr>
</table><br/>

我想要做的是显示一个表格,其中包含每个用户的姓名,电子邮件和角色(权限级别)。每个人的角色应显示在<select></select>标记中,用户应该能够更改它并单击“更新全部”以保存更改。我得到了正确显示所有内容的表,但问题是从表中获取信息到数据库。这是我到目前为止在table

上的内容

如果您想知道,我希望它忽略“模板”角色,因为它可以在以后用作模板。

1 个答案:

答案 0 :(得分:0)

$firebaseArray$firebaseObject具有3向数据绑定。视图,控制器和数据库。

var ref = firebase.database().ref("users");
// var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/users");
$scope.users = $firebaseArray(ref);

当您点击“更新”时,您需要遍历并$save所有更改角色的记录。

首先,我会将您的select更改为:

<select name="{{key}}" ng-options="p.value as p.label for p in permissionLevels" ng-model="value.Role">
</select>

假设你有一系列角色:

$scope.permissionLevels = [
    {
        value: "Default",
        label: "Default",   
    },
    {
        value: "Admin",
        label: "Admin",   
    }
];

然后点击“更新”时你可以调用一些功能:

$scope.update = function() {
    for(var i=0; i<$scope.users.length; i++) {
        // Saves all
        $scope.users.$save(i).then(function(ref) {
            // whatever
        })
    }
}

参考:$firebaseArray $save