2014-02-26 21 views
1

我是Firebase的新用戶。我正在嘗試使用Angular構建可編輯的TreeView,並將其內容保存到Firebase。內容存儲在包含節點列表的「樹」模型中,並且每個節點都包含其子節點列表等。將任意對象(角度模型)同步到Firebase的最簡單方法?

將此對象與FireBase同步的最簡單方法是什麼? 簡單的3-way綁定是否能做到這一點(只需使用。$ bind方法將我的模型綁定到firebase對象)?

這是我的代碼。添加節點時它是目前國內生產的錯誤:

TypeError: Cannot call method 'push' of undefined 

的Javascript:

angular.module("myApp", ["firebase"]). 
controller("TreeController", ['$scope', '$firebase', function ($scope, $firebase) { 
    var treeRef = new Firebase("https://flickering-fire-x.firebaseio.com/my-tree"); 
    $scope.delete = function (data) { 
     data.nodes = []; 
    }; 
    $scope.add = function (data) { 
     data.nodes.push({ 
      text: "", 
      nodes: [] 
     }); 
    }; 
    // Is this correct: ? 
    $scope.remoteTree = $firebase(treeRef); 
    $scope.remoteTree.$bind($scope, "tree"); 
}]); 

HTML:

<script type="text/ng-template" id="tree_item_renderer.html"> 
    <input type = "text" ng-model = "data.text" /> 
    <button ng-click = "add(data)" > Add node </button> 
    <button ng-click="delete(data)" ng-show="data.nodes.length > 0">Delete nodes</button > 
    <ul> 
     <li ng-repeat = "data in data.nodes" 
    ng-include = "'tree_item_renderer.html'" ></li> 
    </ul> 
</script> 
<body ng-app="Application" ng-controller="TreeController"> 
    <ul> 
     <li ng-repeat="data in tree" ng-include="'tree_item_renderer.html'"></li> 
    </ul> 
</body> 
+0

你在哪裏設置$ scope.tree?此代碼是否在沒有Firebase的情況下工作? – rob

+0

在最後2行的javascript(希望)。 – Ognjen

+0

是的,這裏是沒有Firebase的jsfiddle:http://jsfiddle.net/oaprograms/CR9SH/ – Ognjen

回答

0

您嘗試推到未定義數組中的附加功能。

爲避免此錯誤,您必須在使用它之前創建數組!

angular.module("myApp", ["firebase"]). 
controller("TreeController", ['$scope', '$firebase', function ($scope, $firebase) { 
    var treeRef = new Firebase("https://flickering-fire-x.firebaseio.com/my-tree"); 

    data.nodes = []; 

    $scope.delete = function (data) { 
     data.nodes = []; 
    }; 
    $scope.add = function (data) { 
     data.nodes.push({ 
      text: "", 
      nodes: [] 
     }); 
    }; 
    // Is this correct: ? 
    $scope.remoteTree = $firebase(treeRef); 
    $scope.remoteTree.$bind($scope, "tree"); 
}]); 

這將是工作

+0

這應該不是問題,data.nodes是本地的,已經在html中定義。這裏是我的工作小提琴沒有使用firebase:http://jsfiddle.net/oaprograms/CR9SH/ – Ognjen

0

我想通了 - 問題是,火力地堡不保存空數組,只是忽略它們。所以add函數應該檢查data.nodes是否未定義:

$scope.add = function (data) { 
    var newNode = { 
      text: "", 
      nodes: [] 
     } ; 
    if(data.nodes){ 
     data.nodes.push(newNode); 
    }else{ 
     data.nodes = [newNode]; 
    } 
}; 
相關問題