1
Please consider the small angularJs code snippet below.

$scope.myArray = [];
function sampleMethod(){
    $scope.myArray.push({
        name: $scope.name,
        age: $scope.age
    });
    console.log($scope.myArray.name);
};

Here, I was trying to get the scope values name and age and loading it to a scope array inside a controller. But the above program prints nothing. Cant we access and feed scope values to an array from controller? If not possible, how can I do it correctly?

das
  • 669
  • 2
  • 12
  • 22

2 Answers2

0

Your $scope.myArray is an array, not an object.

DO this, $scope.myArray[0].name it should work.

Don
  • 1,334
  • 1
  • 10
  • 18
0

Try like this:

var app = angular.module('app', []);
app.controller('MainController', function($scope) {
    $scope.name = 'Cuco Pérez';
    $scope.age = 37;
    $scope.myArray = [];

    (function sampleMethod() {
        $scope.myArray.push({
            name: $scope.name,
            age: $scope.age
        });
        console.log($scope.myArray[0].name);
    })();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="MainController">
    <h1>Hi, my name is: {{ myArray[0].name }}</h1>    
  </div>  
</div>
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46