简体   繁体   中英

AngularJS Using Function defined in Controller inside Config and Directive

I'm don't have a lot of experience with Angular, and I'm having an issue using a function inside my app.config()

I have a function defined in my controller that is checking for a specific css attribute on my html footer:

app.controller('MyController', function($scope) {

  var footer = $scope.footer;

  $scope.checkSmall = function() {
    if(footer.css("flex-flow") != "row nowrap") {
      return true;
    } else {
      return false;
    }
  };

});

It's being called in a directive here:

app.directive('radio', function() {
  return {
    controller: 'MyController',
    link: function(scope, element, attrs) {
      element.bind('click', function() {
        if(scope.checkSmall()) {
          // stuff
        }
      })
    },
  }
});

And it works fine there. The issue is I would like to use the same function in my app.config()

This is what I have right now:

app.config(function($stateProvider, $urlRouterProvider) {
  // Check screen size
  $urlRouterProvider.otherwise(((checkSmall()) ? '/' : '/full'));

But it obviously tells me that checkSmall() is undefined.

Is there a workaround, allowing me to use the function defined in my controller inside the config? Or should I be going about this a different way?

Thanks for any assistance!

There is no easy way of accessing a function defined on a controller inside the app's config section.

The easiest workaround is to just define the function globally so it can be accessed from app-config, controller and directive in an easy way. Since the function isn't depending on any data or scope variables of the controller this should not be too much of an issue.

Also, you might wanna rethink if it is neccessary to check for the class in the footer both in the config part as well as in the directive again (it is unlikely that the class changes, right?). Also, be aware that if you are rendering your footer with angular, it will not be accessible (yet) when the app's config method runs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM