2015-07-03 20 views
0

我得到這個錯誤:火力地堡.push()錯誤和NG-模型不能正常工作

Error: Firebase .push failed: first argument contains undefined property 'price' 

這是我的控制器:

angular.module('starter') 
.controller('EditPicsController', function($scope,$location,$state) { 

    var itemsRef = new Firebase('https://myapp.firebaseio.com/items'); 
    var itemprice = this.price 
    $scope.createItem = function(itemprice){ 
     console.log(itemprice); 
     var newItemRef = itemsRef.push({'price':itemprice}); 
    }; 
}); 

而且我的模板:

<form> 
    <div class="list"> 
     <label ng-model="price" class="item item-input item-stacked-label"> 
     <span class="input-label">Price</span> 
     <input type="text" placeholder="$200.00" > 
     </label> 
    </div> 

    <button ng-click="createItem(price)" class='button button-dark'> 
     test-additem 
    </button> 
</form> 

我的console.log輸出爲空。

這是怎麼回事?

+0

將'ng-model =「price」'放回到'input'後,使用'itemsRef.push({price:$ scope.price})'將它傳遞給Firebase。 –

回答

2

您應該將ng型號應用於input而不是label

<input ng-model="price" type="text" placeholder="$200.00" > 

代替

<label ng-model="price" class="item item-input item-stacked-label"> 

並在代碼中,你已經創建了一個類,即itemsRefobject。它的object不是array。所以,因爲這條線itemsRef.push({'price':itemprice});你得到錯誤。 push適用於arrays不適用於object

+0

是的,你是對的。我實際上傳了錯誤的代碼。我只是將ng模型添加到標籤元素,因爲我試圖找出錯誤。我原本是在輸入元素上,並且仍然有相同的錯誤。 –

+0

你說'itemsRef'沒有指向數組。它指向一個'Firebase'對象,它定義了一個'push'方法。 –

1

您似乎完全不使用angularJS。

正如在其他答案中提到的,您應該在輸入元素而不是標籤上設置ng-model,因爲那樣您就可以利用angularJS的雙向數據綁定原理。

這是因爲用戶可以在angularJS中與客戶端應用程序進行交互,並且只能更改可編輯的HTML元素的值。

所以這些值是ng-model,並將綁定到您的控制器,並通過控制器中名爲$ scope的膠水暴露。

所以你的HTML將是:

<form> 
<div class="list"> 
    <label class="item item-input item-stacked-label"> 
    <span class="input-label">Price</span> 
    <input ng-model="price" type="text" placeholder="$200.00" > 
    </label> 
</div> 

<button ng-click="createItem()" class='button button-dark'> 
    test-additem 
</button> 

和控制器代碼:

angular.module('starter') 
.controller('EditPicsController', function($scope,$location,$state) { 

    $scope.itemsRef = new Firebase('https://myapp.firebaseio.com/items'); 
    $scope.createItem = function(){ 
     var newItemRef = $scope.itemsRef.push({'price': $scope.price}); 
    }; 
}); 

此外,如果您$scope.price未定義則火力地堡會抱怨,因爲它不會讓您節省值是未定義的,因此設置了一些表單驗證或初始化ng模型($scope.price)與一些值來測試。

更新:您的代碼$scope.itemsRef.push({'price': $scope.price});用於保存到Firebase是絕對正確的,它只是Firebase不喜歡在javascript中定義的所以您的模型$範圍。價格需要有一個價值得到這個工作

0

由於火力地堡不喜歡不確定的屬性是這樣的:

item = { 'name': 'hot dog', 'price': undefined }; 
itemsRef.push(item); 

我做一個快速和骯髒的清理我的對象之前,我推

for(let attr in item){ 
    try { 
     if(item[attr] == undefined) delete item[attr]; 
    } catch(e){} 
} 
itemsRef.push(item); 

這將推動

{ 'name': 'hot dog' } 

和火力很高興: - )..