如何通过firebase数据库中的angularjs点击获取数组元素的唯一ID

时间:2016-02-05 12:31:22

标签: javascript angularjs firebase angularfire

HTML: 
 <div ng-controller="getIdController">
        <div class="container">
            <div class="row">
                <div class="col-md-6">
                    <hr />
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Age</th>
                                <th>Gender</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr ng-repeat="user in userData">
                                <td> {{ user.name }} </td>
                                <td> {{ user.age }} </td>
                                <td> {{ user.gender }} </td>
                                <td><button class="btn btn-warning" ng-click="getObjectId()">Get Id</button></td>
                            </tr>
                        </tbody>
                    </table> 
                </div>
            </div>   
        </div>   
</div>

App Js:

var crudApp = angular.module('crudApp', ['firebase']);
crudApp.controller('getIdController', ['$scope', '$firebaseArray', function($scope, $firebaseArray){

    var ref = new Firebase('https://blistering-fire-4719.firebaseio.com/users');

    $scope.userData = $firebaseArray(ref);    

    $scope.getObjectId = function(){

        $scope.userData.$loaded()
            .then(function(id){ 

            var obj = id;

            console.log(obj);          

        });
    }   
}]);

说明:

好的在这里在firebase我有User表,它有3个对象,每个对象都有唯一的id。目前我正在尝试通过单击html中的Get Id按钮来提取对象的唯一ID。但问题是如果我做console.log(id)函数getObjectId()给我//数组[对象,对象,对象] ..点击对象将我带到它的数据,它的$ id为-K9jyc0K9i28h53d23Uw ..

有没有办法在单击按钮

时获取特定元素的唯一ID

我希望在单击html中的特定元素/对象时为元素显示此唯一ID。

请帮忙。

2 个答案:

答案 0 :(得分:1)

如果您的用户对象上有id属性,您可以直接引用它。您可以将其作为ng-click指令中的参数传递:

<button ng-click="selectUser(user)">

并在您的控制器中:

$scope.selectUser = function(user) {
    console.log(user); // should emit the user object.  is id a property?
}

如果所有对象都使用相同的属性,则可以使用单个函数:

$scope.showObjectId = function(object) {
    alert(object.id);
}

答案 1 :(得分:0)

你可以在html中显示这样的id(在ng-repeat中):

<td> {{ user.$id }} </td>

或将其发送到ng-click功能(在ng-repeat中):

<button class="btn btn-warning" ng-click="getObjectId(user.$id)">Get Id</button> //Just send the id to the function
<button class="btn btn-warning" ng-click="getObjectId(user)">Get Id</button> //Send the etire user object to the function

在你的javascript中你可以像这样使用它:

$scope.getObjectId = function(user){ 
//If you only send the id to this function you can get the entire user object like this (it gives a $firebaseObject i think):
var user = $scope.userData.$getRecord(user);
//Here you can do anything with the user
//Update user data
$scope.UserData.$save(user);
//Remove user
$scope.UserData.$remove(user);
}