简体   繁体   English

使用Angular JS将数据推入对象数组

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

Say I had the following: 说我有以下几点:

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

How would I go about pushing data from a form into the messages array? 我将如何将数据从表单推入message数组? I have a form setup as so: 我有这样一个表单设置:

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

and my Angular as so: 和我的Angular一样:

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

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

Now of course this works because it is pushing it to the $scope.messages array I just defined, but I need to submit it to the $scope.chats messages array. 现在当然可以了,因为它会将其推送到我刚刚定义的$ scope.messages数组中,但是我需要将其提交到$ scope.chats messages数组中。

you can use 您可以使用

$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