Вопрос

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?

Это было полезно?

Решение

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()...

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top