Chris
Chris

Reputation: 5804

Why use .factory in AngularJS instead of declaring as a variable?

Currently learning Javascript and Angular JS. I'm trying to see if I can get around not using .factory by just declaring what it returns as a variable and then referencing it.

Why must I use factory instead of just declaring what it returns as a a function? Is there anyway to get around it.

JAVASCRIPT CODE 1 (MY CODE): http://jsfiddle.net/chrisguzman/s4dBE/4/

  myapp.controller("SampleController",
    function SampleController($scope,$firebase){
        var ref = new Firebase("https://helloworldtest.firebaseio.com/text");
        var service = $firebase(ref);
        service.$bind($scope, "text");
    })

JAVASCRIPT CODE 2 (ORIGINAL CODE): http://jsfiddle.net/chrisguzman/s4dBE/3/

angular.module("sampleApp", ["firebase"])
  .factory("sampleService", ["$firebase", function($firebase) {
    var ref = new Firebase("https://helloworldtest.firebaseio.com/text");
    return $firebase(ref);
  }])
  .controller("SampleController", ["$scope", "sampleService",
    function($scope, service) {
      service.$bind($scope, "text");
    }
  ]);

Bonus question: Is there any other way to write the second script of code differently. The reason I ask is because it would help in understanding it further. In particular, I'd like to see the same task be accomplished without the use of factory, and it would be awesome see a function as the second argument of the controller (as that's what've been exposed to).

Upvotes: 1

Views: 223

Answers (1)

Rob
Rob

Reputation: 1860

The point of the factory is to have a single source point for your data and you can inject that factory in other controllers. You would have to duplicate Firebase in each controller you wanted to use it as opposed to just injecting the factory. For a simple one controller application, this isn't really any issue, but as your application grows, it would become a big issue.

One sample of using a factory:

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

app.factory('FBService',function($firebase) {
    var firebase_url = "https://helloworldtest.firebaseio.com/";

    return {
        ref: function(ref_path) {
            var new_ref = new Firebase(firebase_url + '/' + ref_path + '/');
            return $firebase(new_ref);
        }
    }
});

app.controller('List1Ctrl',function($scope,FBService) {
    $scope.list1 = FBService.ref('list1');
});

app.controller('List2Ctrl',function($scope,FBService) {
    $scope.list2 = FBService.ref('list2');
});

Upvotes: 3

Related Questions