0

I have a.html that defines javascript function inside script tag. Since apparently xxx() is not inside bCtrl, does anyone know how to call xxx()? The point is I can't move function xxx to controller or directive because someone who does not know angular is in charge of this function.

a.html

<html ng-app="myApp">
    <div ng-controller="bCtrl">
    .....
    </div>
    <script>
        (function($) {
            $(function(){
                function xxx () {
                    // do something
                }
            });
        })(jQuery);
    </script>
</html>

bCtrl

angular
.module('myApp')
.controller('bCtrl', [
    '$scope',
    function ($scope) {
        // wanna call xxx() if possible
    }
]);
REI
  • 404
  • 2
  • 5
  • 17
  • There's absolutely no way to call that function from anywhere but inside that inner closure where `xxx` is being defined. It's a scoping issue. – deceze Jul 06 '17 at 08:54
  • 1
    [This question and its answers](https://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background) may be useful. The basic problem you're having is the conflict between the Angular way and the jQuery way. Angular isn't just a library, it's a framework, an approach to building the page/app. Good luck! – T.J. Crowder Jul 06 '17 at 08:56
  • the xxx function is like double private (function inside closure that is inside closure). You need to give a public reference (attach to window or another global reference) to call that function which is a bit hacky. – Volkan Seçkin Akbayır Jul 06 '17 at 08:56

1 Answers1

1

The issue isn't that it's defined within a script tag, it's that it's defined within a function (the callback being passed to $). That means it's entirely private to that function. Unless something makes a reference to it available from outside that function, it's impossible to call it from outside the function.

One way you could make it possible would be to assign it to a global variable:

window.xxx = xxx;

...but in general, global variables are a solution of last resort.

Instead, perhaps you could move that function into a module (ideally, all the things being done in that non-Angular block), and inject a dependency on that module into your controller, and then call it that way.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875