- AngularJs invokes the controller with the $scope object.
- After creating controller, we will create a view for this.
- We use controllers to set the initial state of $scope object and they can be used to add some behavior to $scope object.
- Controller must be used to contain only business logic.
This article is all about AngularJS Controllers. After going through this, you will be able to create simple AngularJS applications using Controller and View model.
The ng-controller directive defines the application controller. When a controller is attached to the DOM via ng-controller, the Angular will instantiate the new controller object using the specified controllers constructor function. A new child scope will be created and made available to the constructor function of specified controller as $scope.
We use controllers to set the initial state of $scope object and they can be used to add some behavior to $scope object. Controller must be used to contain only business logic.
When we create an angular application, first we need to set up the initial state for Angular $scope. We can set up the initial state of a $scope by attaching properties to the $scope object. These properties contain view model. View model is a model that will be represented by the view. All these properties that are attached to the $scope will be available to the template at the point in the DOM where we have registered a controller. AngularJs invokes the controller with the $scope object.
Let us understand with an example: creating an Angular Controller.
Let’s add controller methods (variables and functions). Let’s understand this with an example where we input first name and Last name in the input fields and show full name by combining first name and last name.
First of all we will get the first name and last name into ng-models “firstName” and “lastName” respectively. The we will create a controller “nameController”, where we will pass firstname and lastname to $scope object. We will create $scope.fullName where we will combine firstname and lastname and return . This will be shown in view where we will access the fullName of the controller.