使用Angular JS将数据推送到对象数组中

时间:2016-01-29 09:40:42

标签: javascript angularjs

说我有以下内容:

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

如何将表单中的数据推送到messages数组中?我有一个表单设置如下:

%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消息数组。

1 个答案:

答案 0 :(得分:0)

你可以使用

$scope.text= '';

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