Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS factory mixins

Tags:

angularjs

I've seen some examples where methods are added to the AngularJS controller as mixins. For example:

(function () {
  var app = angular.module('angularjs-starter', []);

  var ParentCtrl = function ($scope, $location) {
    $scope.path = function () {
      return $location.absUrl();
    };
  };

  app.controller('ChildCtrl', function($scope, $injector) {
    $injector.invoke(ParentCtrl, this, {$scope: $scope});
    $scope.url = $scope.path();
  });
})();

I want to be able to add new methods as a 'mixin' to a factory. How can I do that? It's not possible to pass $scope into a factory.

For example, the following doesn't work:

var serv = angular.module('myModule', [])

serv.factory('myService', ['$scope', '$injector', function ($scope, $injector) {
...
like image 442
George Hernando Avatar asked Dec 22 '25 04:12

George Hernando


1 Answers

You can use angular.extend to achieve this, which copies all of the source object's properties into the destination object.

For example:

(function () {
  var app = angular.module('angularjs-starter', []);

  app.factory('CalculatorFactory', function() {
    return {
      add: function(arg1, arg2) {
        return arg1 + arg2;
      }
    }
  });

  app.controller('MainCtrl', function($scope, CalculatorFactory) {
    angular.extend($scope, CalculatorFactory);

    // $scope now has the `add() fn`
    var result = $scope.add(1, 2);
  });

})();
like image 151
Tom Spencer Avatar answered Dec 23 '25 23:12

Tom Spencer