2015-10-08 28 views
0

我在做一個Express Mongo API,並由Angular應用程序使用。如何可以從Angular向Express + Mongodb API發佈itens列表

我的問題是關於張貼itens列表。

這是我蒙戈方案:

var TestSchema = new mongoose.Schema({ 
    title: String, 
    colors: { 
    name: String, 
    hex: Number 
    } 
}); 

如何一個我可以張貼數組的顏色?

我想就這樣說:

<input type="text" ng-model="test.colors[0].name"> 
<input type="text" ng-model="test.colors[1].name"> 
<input type="text" ng-model="test.colors[2].name"> 

但是,被張貼類似的東西並不起作用:

{"1":{"colors":"red"},"2":{"colors":"blue"},"3":{"colors":"green"}} 

謝謝你們。

回答

0

如果你想你的顏色是對象的數組,你應該改變你的架構定義:

var TestSchema = new mongoose.Schema({ 
    title: String, 
    colors: [{ 
    name: String, 
    hex: Number 
    }] 
}); 

比您可以將輸入綁定到某個功能,這將推動色彩,test.colors陣列:

<input type="text" id="colorName" /> 
<input type="button" value="Insert color" onclick="insert()" /> 

function insert() { 
    var color = { 
     name: document.getElementById("colorName"); 
    }; 

    test.colors.push(color); 
} 
+0

但仍然沒有工作。我認爲問題出在以下格式的數據上: {「1」:{「colors」:「red」},「2」:{「colors」:「blue」},「3」:{「colors」 :「green」}} –

+0

您是否嘗試過使用push方法將值插入到數組中? –

0

,您可以嘗試

在HTML:

Color name: <input type="text" id="color" ng-model="color.name" /> 
Hex value: <input type="text" id="hex" ng-model="color.hex" /> 
<button type="button" ng-click="addColor()">Add color with code</button> 
<button type="button" ng-click="saveColorInfo()">Save color info </button> <!--to send to DB --> 

在控制器:

$scope.color = {}; 

$scope.test = {}; 
$scope.test.title= 'test name'; 
$scope.test.colors = []; 

$scope.addColor = function() { 
    $scope.test.colors.push($scope.color); 
}; 

$scope.saveColorInfo = function() { 
    console.log($scope.test); // output will be like-> {title: 'test name', colors: [{name:"black", hex: "#fff"},{name:"red", hex: "#ddd"}]} 
    $http.post('/saveTestColor', $scope.test);// call your api 
}; 

和你的模式應該是:

var TestSchema = new mongoose.Schema({ 
    title: String, 
    colors: [{ 
    name: String, 
    hex: String 
    }] 
}); 
相關問題