Error: cribsFactory.getCribs is not a function

0

I have this controller

 angular
        .module("ngCribs").controller("cribsController", function ($scope, cribsFactory) {
        $scope.cribs = cribsFactory.getCribs(); 
    });

and this factory

angular.module("ngCribs")
        .factory("cribsFactory", function (){
    var cribsData = [
        {
            type: "Apartamento",
            price: 22000,
            andress: "Estrada do Nagao",
            description: "Casa excelente, 4 quartos"

        },
        {
            "type": "Casa",
            price: 320.000,
            andress: "Centro, Mogi",
            description: "Casa excelente, 2 quartos"

        },
        {
            "type": "Apartamento",
            price: 18000,
            andress: "Cesar De Souza",
            description: "Casa excelente, 4 quartos"

        }
    ];

    function getCribs() {
        return cribsData;
    }

    return {
        getCribs: getCribs()
    };
});

The error is to call the getCribs of the message that it is not a function

  
    

Error     Error: cribsFactory.getCribs is not a function

  
    
asked by anonymous 03.09.2017 / 07:18

1 answer

0

In angular factory has to return an object. Then create an object inside your factory , example:

var factory = {};

You can add methods to your object, for example:

factory.alertOla = function() {
  alert("Olá!!");
}

factory.alertBomDia = function() {
  alert("Bom Dia!!");
}

Example of operation.

var factory = {};

factory.alertOla = function() {
  alert("Olá!!");
}

factory.alertBomDia = function() {
  alert("Bom Dia!!");
}
<button onclick="factory.alertOla()">Diga Olá</button>
<button onclick="factory.alertBomDia()">Diga Olá</button>

Solution

var app = angular.module('myApp', []);

app.controller("cribsController", function($scope, cribsFactory) {
    $scope.cribs = cribsFactory.getCribs();
});

app.factory("cribsFactory", function() {
    var factory = {}; // Cria um objeto com nome de: factory
    var cribsData = [{
            type: "Apartamento",
            price: 22000,
            andress: "Estrada do Nagao",
            description: "Casa excelente, 4 quartos"

        },
        {
            "type": "Casa",
            price: 320.000,
            andress: "Centro, Mogi",
            description: "Casa excelente, 2 quartos"

        },
        {
            "type": "Apartamento",
            price: 18000,
            andress: "Cesar De Souza",
            description: "Casa excelente, 4 quartos"

        }
    ];

    // Adiciona um método ao objeto.
    factory.getCribs = function() {
        return cribsData;
    }
    // Retorna o objeto.
    return factory;
});
<div ng-app="myApp" ng-controller="cribsController">
{{cribs}}
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Reference

  • Working with Objects
03.09.2017 / 08:09