Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring controllers in AngularJS

I've seen that on AngularJS tutorials, that some people declare their controller functions like so:

function FirstController($scrope) {
    // do something with $scope
}

and other have done it like this:

var FirstController = function ($scope) {
    // do something with scope
}

Which way is the best way to declare a controller in your JS file, that will work best with the latest version of AngularJS ( right now 1.0.7 ), as in what are the best practices? Or does it not really matter?

like image 678
Games Brainiac Avatar asked Jul 30 '13 17:07

Games Brainiac


People also ask

Can you create controller in AngularJS?

In AngularJS, a controller is defined by a Javascript construction function, which is used in AngularJS scope and also the function $scope) is defined when the controller is defining and it returns the concatenation of the $scope. firstname and $scope. lastname.

What are the controllers in AngularJS?

AngularJS applications are controlled by controllers. The ng-controller directive defines the application controller. A controller is a JavaScript Object, created by a standard JavaScript object constructor.

Why are controllers used in AngularJS?

AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is defined using ng-controller directive. A controller is a JavaScript object that contains attributes/properties, and functions.

Can we have two controllers in AngularJS?

An AngularJS application can contain one or more controllers as needed, in real application a good approach is to create a new controller for every significant view within the application. This approach will make your code cleaner and easy to maintain and upgrade. Angular creates one $scope object for each controller.


2 Answers

myApp.controller('myControl',['$scope',function($scope){
    $scope.controlname = "Something";
}]);
like image 194
Mani maran Avatar answered Sep 21 '22 20:09

Mani maran


The recommended way of declaring Controllers is using the array notation:

 someModule.controller('MyController', ['$scope', 'dep1', 'dep2', function($scope,  dep1, dep2) {
     ...
     $scope.aMethod = function() {
     ...
    }
  ... 
}]); 

according to angularJS site : https://docs.angularjs.org/guide/di

like image 44
Alexandr Avatar answered Sep 20 '22 20:09

Alexandr