0 votes
in Angular by
What are Controllers and Need of ng-controller and ng-model in Angular?

1 Answer

0 votes
by

Controllers are simple JavaScript function which provides data and logic to HTML UI. As the name says controller, they control how data flows from the server to HTML UI.

Image 3

For example, below is simple Customer controller which provides data via CustomerName and CustomerCode property and Add/ Update logic to save the data to database.

Note: Do not worry too much about the $scope, we will discuss the same in the next question.

JavaScript

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

ng-controller is a directive. Controllers are attached to the HTML UI by using the ng-controller directive tag and the properties of the controller are attached by using ng-model directive. For example, below is a simple HTML UI which is attached to the Customer controller via the ng-controller directive and the properties are binded using ng-model directive.

HTML

<div ng-controller="Customer">
<input type=text id="CustomerName"  ng-model="CustomerName"/><br />
<input type=text id="CustomerCode"  ng-model="CustomerCode"/>
</div>

Related questions

0 votes
asked Sep 17, 2023 in Angular by DavidAnderson
0 votes
asked Sep 22, 2023 in Angular by DavidAnderson
...