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
    }
]);
3
  • 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. Commented Jul 6, 2017 at 8:54
  • 1
    This question and its answers 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! Commented Jul 6, 2017 at 8: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. Commented Jul 6, 2017 at 8:56

1 Answer 1

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.

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

Comments

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.