Peterson Peterson - 2 months ago 8
AngularJS Question

Simple factory call giving error in AngularJs

In a simple example, I am expecting console to ping me "USA". Instead I am getting an error. Can someone help fix it?

SNIPPET:

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>

<body ng-app="myApp" ng-controller="myCtrl">
<script>
//module declaration
var app = angular.module('myApp',[]);
//controller declaration
app.controller('myCtrl',function($scope, myFactory){
var a = myFactory();
console.log(a.country);
});

//factory declaration
app.factory('myFactory',function(){
var obj = {};
obj.country = "USA";
return obj;
});
</script>
</body>
</html>


Error:

enter image description here

Answer

try this

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> 


<body ng-app="myApp" ng-controller="myCtrl"> 
<script>
//module declaration
var app = angular.module('myApp',[]);
//controller declaration
app.controller('myCtrl',function($scope, myFactory){
    var a = myFactory;
    console.log(a.country);
});

app.factory('myFactory',function(){
    var obj = {};
    obj.country = "USA";
    return obj;
});
</script> 
</body>