Error: cribsFactory.getCribs is not a Function

Asked

Viewed 90 times

0

I have this controller

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

and that 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()
    };
});

error is to chaamr the getCribs of the message that is not a function

Error Error: cribsFactory.getCribs is not a Function

1 answer

0


Angular factory have to return an object. Then create an object within your factory, example:

var factory = {};

You can add methods to your object, example:

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

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

Working example.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.