Angularjs Examples

AJS Examples


What is controller and how to create controller in AngularJS

In this AngularJS basic example you will learn what is controller and how to create controller in AngularJS. A controller is a simple Javascript function that is used to build a model for the view.

Here you can view the output of the example and you can also "try it yourself" by clicking on "Live Demo" button given at the bottom.

Syntax1

var myController = function($scope){
	$scope.yourProperty = 'This is from controller';
}

Syntax2

function myController($scope) {  
  $scope.yourProperty = 'This is from controller';  
} 

Syntax3

var app = angular.module("moduleName",[]);
app.controller('myController', ['$scope', function($scope) {  
  $scope.yourProperty = 'This is from controller';   
}]); 

Access controller in DOM element

<h1 ng-controller="myController">Message from contgroller  {{  yourProperty  }}</h1>

How to create controller in AngularJS

<html ng-app="moduleName">
<head> 
<title>My first AngularJS code</title>
<Script SRC="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js"></Script>
<script> 
    var app = angular.module("moduleName",[]);
	var myController = function($scope)	{
		$scope.yourProperty = 'This is from controller';
	}
</script>
</head>
<body>
<h1 ng-controller="myController">Message from contgroller  {{  yourProperty  }}</h1>
</body>
</html>