0

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???

3 Answers 3

1

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

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

Comments

0

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

Comments

0

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

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.