Push in JSON Object Angularjs

Asked

Viewed 938 times

1

How do I add 1 item to a json object in Angularjs.
In case I have: {COD: 29, MOTIVO: "teste"}
And I’d like you to stay: {COD: 29, MOTIVO: "teste", ID : 12345789}

I tried it this way:

$scope.cadastroSolicitacao = function(values){
    $scope.v = values;
    $scope.v.push({MATRICULA : '123456789'})
    //console.log($scope.v);
};

In the above case, when I clicked the button containing the form it would run the function cadastroSolicitacao take the values of it and add this item MATRICULA, but I was unsuccessful.

2 answers

2


A simple example with is to access the object and create a new item with those that already exist:

var app = angular.module('app', []);
app.controller('ctrl', ['$scope',
  function($scope) {
    $scope.v = [{
      COD: 29,
      MOTIVO: "teste"
    }, {
      COD: 30,
      MOTIVO: "teste"
    }];
    $scope.addMatricula = function(obj, value) {
      obj.MATRICULA = value;      
      console.log($scope.v);
    }
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
  <div  ng-repeat="value in v">
    {{value.COD}} {{value.MOTIVO}} {{ value.MATRICULA }}
    <input ng-model="MAT" /> 
    <button type="button" ng-click="addMatricula(value,MAT)">Adiconar Matricula</button>
  </div>
</div>

1

The method .push() serves only to insert a new item into a Array.

To insert a new attribute into an object you can do so:

$scope.v.MATRICULA = '123456789'

or

$scope.v['MATRICULA'] = '123456789'

There’s no way to do that in angular, that is javascript.

  • 1

    "There’s no way to do this at the angle, that’s javascript". What? Angular is Javascript.

  • @jbueno just what I wanted to explain. To answer the first line of the question: "How do I add 1 item in a json object in Angularjs."

Browser other questions tagged

You are not signed in. Login or sign up in order to post.