0

I have a function that two controllers will be using, and instead of both of them having the same source code for the same function, I want it in one place and just inject the controller parameters (or perhaps the controller itself this). These three may exist in three separate files/modules.

.controller('FirstCtrl', function() {
    this.search = function(this) {
        find(this);
    };
});


.controller('SecondCtrl', function() {
    this.seek = function(this) {
        find(this);
    };
});


var find = function(controller) {
    .
    .
    .
};

Is this the best way? How about if I have services in my controllers like $http or $scope, and the function find would depend on these services? How do I inject these angular specific services to a plain JavaScript function not defined in an AngularJS module?

2 Answers 2

1

There are a few ways to do it; one may be:

.factory("findMixin", function() {
    return {
        find: function() {
            // your implementation; `this` will be the controller
        }
    };
})

.controller("SomeCtrl", ["$scope", "findMixin", function($scope, findMixin) {
    angular.extend(this, findMixin);
    // here `this`, i.e. the controller, has received the methods from the mixin
    ...
})

The same principle (angular.extend) can be applied to the $scope, if you want find to be mixed into the scope.

Sign up to request clarification or add additional context in comments.

Comments

1

You can add a service:

.factory('find', [ function() {
    return function(controller, scope) {
        // ...
    };
}]);

And inject it into the controllers:

.controller('FirstCtrl', ['find', function(find) {
    this.search = function(this) {
        find(this);
    };
}]);


.controller('SecondCtrl', ['find', function(find) {
    this.seek = function(this) {
        find(this);
    };
}]);

4 Comments

Thanks. And how about when function find would need a service specific to the controller, say $scope? How do I go about doing that?
@menorah84 You can inject the $scope into the service factory as well: .factory('find', ['$scope', function($scope) { ... }]);. I updated the answer.
as i know you can't inject $scope into a service or factory. The only scope you can inject is a $rootScope.
@MajoB Ah yes, didn't think of that. But it should be as easy as sending the current scope as an argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.