user3400087
user3400087

Reputation: 29

Basics of AngularJS Controller definition syntax

While going through AngularJS sample application, I notice things like:

Define(['app'], function (app) {
var customersController = function ($scope, $location, $filter, dataService,   modalService) {...}
app.register.controller('CustomersController',
['$scope', '$location', '$filter', 'dataService', 'modalService', customersController]);

I do not understand the complete syntax, for example I do not know what this line means or do?

Define(['app'], function (app)

Where I can learn this basic stuff?

Upvotes: 1

Views: 356

Answers (2)

ms87
ms87

Reputation: 17492

That's mostly requireJS semantics. In requireJS Define basically creates a module. Here we declare a module, in this case a controller, the first array is dependencies for the module, in this case it's only app, our angular app definition. The dependencies (first parameter of define, the array) will be resolved and passed into the function (our controller), here app is passed to the controller:

define(['app'], function (app) {

The line below actually creates the function acting as our controller: var customersController = function ($scope, $location, $filter, dataService, modalService) {}

The above is just like any angular controller definition, with the dependencies passed into the controller. Below is where we hook up the controller function to the app dependency requireJS brought in for us. We're telling angular to create a controller called CustomersController, the second parameter, the array with strings is defining the controllers dependencies as hard coded strings, this to make the script minification safe, since string won't be tampered by the minifier, for example in angular if your controller's scope gets minified to something like s, that will break your app.

app.register.controller('CustomersController', ['$scope', '$location', '$filter', 'dataService', 'modalService', customersController]);

The whole point of this approach is to allow lazy (on demand) loading of modules/controllers in angular, if you're not building a huge app then there's no need. I for one found this approach by Dan Wahlin extremely helpful.

Here is more articles to help you:

AngularJS - Controllers, Dependencies, and Minification

RequireJS API

Upvotes: 2

j.wittwer
j.wittwer

Reputation: 9497

This code is from an article titled "Dynamically Loading Controllers and Views with AngularJS and RequireJS", which in my opinion is not basic stuff. The author has several tutorials intended for beginners, including this video.

I, for one, like the lessons at egghead.io.

Upvotes: 0

Related Questions