What is the correct way to wrap Angularjs code in a closure?

159 views Asked by At

I have a simple application outlined in this question: Angular scope not affecting ng-show as expected

Which exposes my application via global variables, this is obviously not ideal.

I have tried wrapping the Angularjs code in a closure but I get errors in the browser telling me that the objects I am trying to access aren't accessable.

(function() {

// App code here

});

Is there a way to expose my app so with the current layout it functions correctly or do I need to change the whole struction of my app to achieve this.

I am ideally trying to reduce global variable pollution while keeping the app structure the same in both the html and js.

1

There are 1 answers

1
Jeffrey A. Gochin On BEST ANSWER

You are missing the call part.

Here is one format, there are a few others.

(function (a, b){
    //Do stuff with `a` and `b`
})("a", "b");

Note the final pair of parens. Any parameter that you define, and later pass in are global within the scope.