簡體   English   中英

使用Angular JS將數據推入對象數組

[英]Push Data Into An Objects Array With Angular JS

說我有以下幾點:

.controller("chatCtrl", function($scope, $timeout, $rootScope) {
  $scope.chats = [{
    id: 1,
    username: "Aname",
    avatar: "imgsrc",
    messages: [
      "Hello",
      "World"
    ]
  }];

我將如何將數據從表單推入message數組? 我有這樣一個表單設置:

%form{"ng-submit" => "add()"}
%input{:type => "text", :placeholder => "Enter a message", "ng-model" => "text"}
%input{:type => "submit", :value => "Send"}

和我的Angular一樣:

$scope.text = '';
$scope.messages = [];

$scope.add = function() {
  if($scope.text) {
    $scope.messages.push(this.text);
    $scope.text = '';
    console.log($scope.messages);
  }
}

現在當然可以了,因為它會將其推送到我剛剛定義的$ scope.messages數組中,但是我需要將其提交到$ scope.chats messages數組中。

您可以使用

$scope.text= '';

$scope.add = function() {
   $scope.chats[0].messages.push($scope.text);
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM