5

I have a very small number of functions that I need to use like this:

data-ng-disabled="_isEmpty(grid.view) || view != 'preview'"

What I did was:

$scope._isEmpty = _.isEmpty;

so that the _isEmpty is actually the lodash function.

Is this a reasonable thing to do? Also if so then where would be a good place for me to code the above line? Should I code that in my appController. Also should I attach the ._isEmpty to $scope or $rootscope? I have heard people talking about making a service and then injecting this. But for a few lines of code this seems overkill.

  • 1
    Possible duplicate of [How can I add some small utility functions to my AngularJS application?](http://stackoverflow.com/questions/19614545/how-can-i-add-some-small-utility-functions-to-my-angularjs-application) –  Dec 06 '15 at 02:20

2 Answers2

16

It all depends on where this code is required. If it is heavily reliant on, or required by a particular data object or view, then it most likely belongs in a controller. If inside a controller, $scope should be used by any value you want to reference in a view.

If however, you are writing generic functions used throughout your application, then they should be put in something like a service, and injected where required. Most of the time if you find yourself using $rootScope, the code should probably be in a service. Services aren't really overkill, as you can see below:

angular.module('myapp.services.something', [])
    .factory('myService', [function () {
        return {
            myFunc: function (someArg) {
                console.log(someArg);
            }
        };
     }]);

You could put any number of generic helper functions for example in a service like this, and inject them into any controller that requires their use.

Matt Way
  • 32,319
  • 10
  • 79
  • 85
  • 1
    Thank you for this, perfect solution in my situation. Also IMO the cleanest, most Angular-standards-compliant one. – Grüse Nov 20 '14 at 11:45
-1

Though generally not recommended, I could see this kind of problem solved with putting the functions into the rootscope. Then putting the line $scope._isEmpty = _.isEmpty; in every controller would not be necessary anymore. A far better way for me would be to recode the utility functions into directives, even if involves some coding. Another way to solve the problem is to use services.

zszep
  • 4,450
  • 4
  • 38
  • 58
  • If I code into the top most controller then is that function not available to all the other controllers below that ? –  Feb 02 '14 at 06:45
  • Yes it is (except for isolate scope in directives). And there is an implictly created topmost controller for the application (besides your defined controllers) that has $rootsCope as its scope. Scopes are prototypically inherited in angulars. – zszep Feb 02 '14 at 06:52