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) {
...
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);
});
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With