1

I have defined a function within my controller, which i want to call in a module. How is this possible?

The controller:

var App = angular.module('App',['ngResource','App.filters']);

App.controller('ExerciseCtrl', ['$scope','$http', function($scope, $http) {

    $scope.toggleOn = function (arr, id) {
        // Some code
    }; 

}]);

And the module:

angular.module('App.filters', []).filter('someFilter', [function () {
    return function () {
        someArray = [];
        toggleOn(someArray, 1); // Wish to call this function
    };
}]);

I want to call toggleOn within the module.

2
  • Can you please explain what exactly you are trying to achieve with this code? At a first glance, it doesn't seem like the "angular way" of doing things to call a scope function from within a filter. Even if you wished to do this, using angular services would probably be the way to go. Commented Apr 16, 2014 at 20:26
  • @ppa, its dummy code, i did not want to paste 900 lines of code in my question. I have a bunch of functions within my controller which i intended to use. Can you please explain how i should do this instead, if its not best-practice to call functions from a controller within the filter? Commented Apr 16, 2014 at 20:29

2 Answers 2

1

Off the top of my head, maybe something like this:

var App = angular.module('App',['ngResource','App.filters']);

App.service('toggleService', function(){
    var service = {
        toggleOn: function(arr, id){

        }
    };

    return service;
});

App.controller('ExerciseCtrl', ['$scope','$http', 'toggleService', function($scope, $http, toggleService) {

    $scope.toggleOn = toggleService.toggleOn;

}]);

angular.module('App.filters', []).filter('someFilter', ['toggleService', function (toggleService) {
    return function () {
        someArray = [];
        toggleService.toggleOn(someArray, 1); // Wish to call this function
    };
}]);
Sign up to request clarification or add additional context in comments.

Comments

0
angular.module('App.filters', []).filter('someFilter', [function () {
    return function (scope) {
        someArray = [];
        scope.toggleOn(someArray, 1); // Wish to call this function
    };
}]);

And pass scope to filter

<span ng-controller="ExerciseCtrl">{{someFilter | this}}</span>

1 Comment

I forgot var App = angular.module('App',['ngResource','App.filters']); which i have defined. Check my edit

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.