user3574939
user3574939

Reputation: 829

Angular controller syntax

While reviewing angular interview question and answers, I noticed that the author has written the controller's syntax as follows:

function Customer($scope)
{
        $scope.CustomerName = "Shiv";
        $scope.CustomerCode = "1001";
        $scope.Add = function () {
        }
        $scope.Update = function () {
        }
}

I'm accustom to writing controllers in this way:

app.controller('Customer', function($scope) {
  $scope.CustomerName = "Shiv";
  $scope.CustomerCode = "1001";
  $scope.Add = function () {}
  $scope.Update = function () {}
});

How would I use the authors controller syntax in an angular project???

Upvotes: 0

Views: 118

Answers (3)

Jairo Dev
Jairo Dev

Reputation: 61

The author is simply using a named function, instead of directly passing an anonymous function like you did.

app.controller('Customer',Customer);

function Customer($scope) {
  ...
}

Also, I'd recommend looking into dependency injection, which is an Angular best practice required by its Strict Mode. Like so...

app.controller('Customer',Customer);

// Dependencies declared here
// This tells angular what to inject into your controller
Customer.$inject = ['$scope'];

// Controller Constructor Function
// You can now safely use $scope.
function Customer($scope) {
  ...
}

Check out Using StrictDI in Angular docs. At the bottom there's a JS example for BadController, GoodController1, and GoodController2

The first GoodController1 would be an improvement to your style. The author went for the GoodController2 syntax

Upvotes: 0

BSmall
BSmall

Reputation: 28

John Papa who is the nationally recognized "guru" on Angular and he recommends creating controllers as in your first example. See HERE for usage.

Upvotes: 1

chairmanmow
chairmanmow

Reputation: 650

app.controller('Customer',Customer($scope))

Upvotes: 0

Related Questions