Daniel Tate
Daniel Tate

Reputation: 2163

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

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.

Upvotes: 1

Views: 141

Answers (1)

Jeffrey A. Gochin
Jeffrey A. Gochin

Reputation: 964

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.

Upvotes: 2

Related Questions