AngularJS - Controllers

By xngo on August 21, 2019

The ng-controller directive defines the application controller. It is within the controller that you control the data of the AngularsJS application. The controllers are simply JavaScript objects.

Here is an example of the controller myData that returns a name and a list of fruits.

<div ng-app="myApp" ng-controller="myData">
    <p>My name is {{ name }}.</p>
    <p>I love {{ fruits[1] }}.</p>
</div>
 
<script>
var app = angular.module("myApp", []);
app.controller('myData', function($scope) {
    $scope.name = 'Joe';
    $scope.fruits = ['apple', 'pineapple', 'banana'];
});
</script>

Output

My name is Joe.
I love pineapple.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.