Dyon
Dyon

Reputation: 195

Angular Factory Injection not working

im trying to get Angular to work at a really basic level. But i just dont get it. Im doing all the tutorial and everything. It kills me.

Here is what im doing:

1.) HTML

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
    <script src="js/app.js"></script>
    <script src="js/Controller.js"></script>
    <script src="js/friendsFactory.js"></script>


</head>
<body>
<div ng-app="friendsApp">
    <div ng-controller="friendsController">
        <h3>{{girlFriendName}}</h3>
    </div>


</div>
</body>
</html>

2.) App.js

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

3.) Controller.js

friendsApp.controller('friendsController', ['$scope','friendsFactory', function($scope, friendsFactory){

    $scope.girlFriendName = friendsFactory.girlFriend();

}]);

4.) Friendsfactory.js

friendsApp.factory('friendsFactory',  function (){

  this.girlFriend = function(){

      var name = "Girlfriends Name";

      return name;

  }

});

I wanted to try this at a very basic level but now i have spent 5 hours trying to get a name from the Factory to the Controller. If i write the name manually into the controller it works, so the controller get called.

Can anybody tell me where i am thinking wrong here?

Thank you very much!

Upvotes: 0

Views: 880

Answers (2)

himaja
himaja

Reputation: 216

You have created the factory methods but didn't return it.

    friendsApp.factory('friendsFactory',  function (){
        this.girlFriend = function(){
            var name = "Girlfriends Name";
            return name;
        }
        return {
           girlFriend : this.girlFriend
        }
    });

Upvotes: 1

Ajay Kumar
Ajay Kumar

Reputation: 1164

Modify factory code:

friendsApp.factory('friendsFactory',  function (){

  this.girlFriend = function(){

      var name = "Girlfriends Name";

      return name;

  }

});

To:

friendsApp.factory('friendsFactory',  function (){

  function girlFriend(){
      var name = "Girlfriends Name";
      return name;
  }

  return {
     girlFriend: girlFriend
  }
});

Upvotes: 3

Related Questions