Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function added with Restangulars extendModel is undefined?

I have a service like this:

.factory('Car', function(Restangular) {

    var baseCars = Restangular.all('cars');

    Restangular.extendModel('cars', function(obj) {
        obj.extraMethod = function() { console.log('method added'); };
        return obj;
    });

    return {
        show: function(id) {
            return baseCars.one(id).get();
        }
    };
});

and a controller like this:

.controller('CarCtrl', function ($scope, $stateParams, Car) {

    Car.show($stateParams.id).then(function(car) {
        $scope.car = car;
        $scope.car.extraMethod();
    });
});

However, this results in an undefined is not a function error at $scope.car.newMethod().

Does anyone know why this is and how to get it to work?

like image 430
acrmuui Avatar asked Mar 13 '14 12:03

acrmuui


1 Answers

Actually you are too close but you missing that when you write

Restangular.extendModel('cars', function(obj) {
    obj.extraMethod = function() { console.log('method added'); };
    return obj;
});

this only extend object with 'cars' route...

but your return object's route is whatever your id parameter...

try this code...

 factory('Car', function(Restangular) {

    Restangular.extendModel('cars', function(obj) {
        obj.extraMethod = function() { console.log('method added'); };
        return obj;
    });

    return {
        show: function(id) {
            return Restangular.one('cars', id).get();
        }
    };
  }

this time return object's route is cars and it will have extramethod()...

like image 111
Poyraz Yilmaz Avatar answered Sep 20 '22 02:09

Poyraz Yilmaz