Push in JSON Object AngularJS

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} Home I tried the following:

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

In the above case, when I clicked on the button that contains the form it would execute the function cadastroSolicitacao get the values of it and add this item MATRICULA , but did not succeed.

    
asked by anonymous 10.02.2017 / 20:47

2 answers

2

A simple example with tag 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><divng-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>
    
10.02.2017 / 21:10
1

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

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

$scope.v.MATRICULA = '123456789'

or

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

There is no way to do this in angular , this is javascript .

    
10.02.2017 / 20:51