简体   繁体   中英

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? 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:

$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.

you can use

$scope.text= '';

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM