Search code examples
angularjsangular-controller

Why is my variable undefined in the controller?


Here is my controller code, As soon as the function init() runs, it returns undefined for this.customers.

myApp.controller('OrdersController',['$routeParams', function ($routeParams) {
var customerId = $routeParams.customerId;
this.orders = null;


this.customers = [
    {joined: '2012-12-03', name: 'Amit', city: 'Delhi', orderTotal: 34.53,orders: [{id:1,product:'shoes',total:'34.53'}]},
    {joined: '1995-04-24', name: 'Ravi', city: 'Mumbai',orderTotal: 45.34,orders: [{id:2,product:'socks',total:'53.51'}]},
    {joined: '2003-03-21', name: 'Flish', city: 'Lonavla', orderTotal: 134.323,orders: [{id:3,product:'books',total:'43.55'}]},
    {joined: '2003-10-14', name: 'Meahe', city: 'Pune', orderTotal: 12.33,orders: [{id:4,product:'eraser',total:'12.33'}]}
];

function init() {
    console.log('infunc',this.customers);
    //search the customers for customerId
    for(var i=0; i < this.customers.length; i++){
        if(this.customers[i].orders[0].id === parseInt(customerId)) {
            this.orders = this.customers[i].orders;
        }
    }
}

init();

}]);

Solution

  • It's better define var vm = this then use instead of this.

    myApp.controller('OrdersController',['$routeParams', function ($routeParams)        {
    var vm = this; 
    var customerId = $routeParams.customerId;
    vm.orders = null;
    
    vm.customers = [
        {joined: '2012-12-03', name: 'Amit', city: 'Delhi', orderTotal: 34.53,orders: [{id:1,product:'shoes',total:'34.53'}]},
        {joined: '1995-04-24', name: 'Ravi', city: 'Mumbai',orderTotal: 45.34,orders: [{id:2,product:'socks',total:'53.51'}]},
        {joined: '2003-03-21', name: 'Flish', city: 'Lonavla', orderTotal: 134.323,orders: [{id:3,product:'books',total:'43.55'}]},
        {joined: '2003-10-14', name: 'Meahe', city: 'Pune', orderTotal: 12.33,orders: [{id:4,product:'eraser',total:'12.33'}]}
    ];
    
    function init() {
        console.log('infunc',vm.customers);
        for (var i=0; i < vm.customers.length; i++) {
            if ($scope.customers[i].orders[0].id === parseInt(customerId)) {
                vm.orders = vm.customers[i].orders;
            }
        }
     }
    
      init();
    }]);