ng-controller directive in AngularJS


To attach a controller class to the view, we use ng-controller directive. It is the key aspect in AngularJS model view controller architecture.

Example:
Quantity : {{Qty}}
Unit Price : {{UnitPrice}}
Total Price : {{Qty*UnitPrice}}

<div ng-app="SampleApp" ng-controller="SampleCntrl"> Quantity : {{Qty}}<br /> Unit Price : {{UnitPrice}}<br /> Total Price : {{Qty*UnitPrice}}<br /> </div> <script> var myapp = angular.module("SampleApp", []); myapp.controller("SampleCntrl", function ($scope) { $scope.Qty = 5; $scope.UnitPrice = 6; }); </script>

MVC Architecture in AngularJS
  • Model : Models are the properties of a scope
  • View : HTML that is rendered into the View
  • Controller : The ng-controller directive specifies the controller class. It contains business logic JavaScript methods, variables, properties.
Source Code:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script> </head> <body> <div ng-app="SampleApp" ng-controller="SampleCntrl"> Quantity : {{Qty}}<br /> Unit Price : {{UnitPrice}}<br /> Total Price : {{Qty*UnitPrice}}<br /> </div> <script> var myapp = angular.module("SampleApp", []); myapp.controller("SampleCntrl", function ($scope) { $scope.Qty = 5; $scope.UnitPrice = 6; }); </script> </body> </html>