Search code examples
javascriptangularjsarraylistangularjs-scopeview-scope

loading scope value into an array doesnt work in angularjs


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?


Solution

  • 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>