How to use controllers with AngularJS

AngularJS is a client-side JavaScript framework that lets us extends HTML DOM with additional attributes and makes it more responsive to user actions. A controller contains attributes and functions. In this tutorial I will explain to you how you can use the controllers with AngularJS.

Add this code <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script> between the head tags in your page.

Next, create a new div:

<div ng-app="" ng-controller="New">

</div>

Next, you must create a function for your controller:

<script language="javascript">

function New($scope)

{

$scope.messagge = "New Messagge";

}

</script>

Now, to display the $scope.messagge value in your controller div, use:

<div ng-app="" ng-controller="New">

<span ng-bind="messagge"></span>

</div>

If you want to add the $scope.messagge value in a input, use:

<input type="text" ng-model="messagge"> instead <span ng-bind="messagge"></span> or you can use them together.

You you want to use a function in your controller, you can do it in this way:

<div ng-app="" ng-controller="New">

{{messagge.c()}}

</div>

<script language="javascript">

function New($scope)

{

$scope.messagge = {

a:"John",

b:"30",

c:function()

{

var object = $scope.messagge;

return object.a+" has "+object.b+" years";

}

};

}

</script>

Output: John has 30 years









Leave a Comment