Reputation: 829
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
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