Angular firebase使用3向绑定过滤数据

时间:2014-02-14 00:23:51

标签: angularjs firebase

我有一个带有数据数组的简单角度应用程序:

app.js

var myApp = angular.module('myApp', []);

myApp.controller('Ctrl', function ($scope) {
    $scope.data = [
      {name: "Alice", age: 28},
      {name: "Bob", age: 55},
      ...
    ];
});

的index.html

<input type="text" ng-model="data.search">
<table>
  <tbody>
     <tr ng-repeat="row in data | filter:data.search">
        <td>{{ data.name }}</td>
         <td>{{ data.age }}</td>
      </tr>
   </tbody>
 </table>

现在,我想开始使用firebase服务来体验酷炫的3路绑定。所以我做了这样的事情:

app.js

var myApp = angular.module('myApp', ['firebase']);

myApp.controller('Ctrl', function ($scope) {
    var ref = new Firebase("https://<myapp>.firebaseio.com/");
    // assume there is already data in here similar to above
    $scope.data = $firebase(ref);
});

当然现在我的搜索过滤器会中断,因为$scope.data是一个对象而不是一个数组。当然我可以转换数据,但这会破坏自动3向绑定。

所以我的问题是 - 如何在保持三向关系的同时将过滤器应用于此数据?

2 个答案:

答案 0 :(得分:3)

您可以先使用orderByPriority过滤器将对象转换为数组:

<tr ng-repeat="row in data | orderByPriority | filter:data.search">

或者,您可以使用控制器中的过滤器来确保$ scope.data是一个开头的数组。

答案 1 :(得分:1)

Anant的建议有效。工作小提琴:http://jsfiddle.net/rwk1/vqVw7/

无法发表评论。

HTML

<div ng-app="myApp">
  <div ng-controller="testController">
    <input type="text" ng-model="search.searchText"></input>

    <div>
        <ul ng-repeat="person in people | orderByPriority | filter:search.searchText">
            <li>name:{{ person.name }}</li>
            <li>age:{{ person.age }}</li>
        </ul>

        <input type="text" placeholder="name" ng-model="newPerson.name"/>
        <input type="text" placeholder="age" ng-model="newPerson.age"/>
        <button type="submit" ng-click="addPerson()">Add New Person</button>
    </div>
  </div>      
</div>

JS

var myApp = angular.module('myApp', ["firebase"]);

myApp.controller('testController', function ($scope, $firebase) {
    $scope.data = [{
        name: "Alice",
        age: 28
    }, {
        name: "Bob",
        age: 55
    }];

    var peopleRef = new Firebase("https://sqt.firebaseio.com/people");
    // Automatically syncs everywhere in realtime
    $scope.people = $firebase(peopleRef);

    $scope.addPerson = function(){
        $scope.people.$add($scope.newPerson);
        $scope.newPerson = "";
    };