Learn about Controllers in AngularJS

0
2488
controllers-740X296

controllers-740X296

AngularJs is a front-end framework based on the MVC model – Model, View, Controller. It’s built on top of Javascript and jQuery. The model represents the data source, the View the webpage, and the Controller to the connection between the two. Maintaining that separation makes our code easier to update and manage. Angular allows us to extend HTML tags and attributes with directives, whichbind the data directly to HTML objects. In order to use the AngularJS library, we need to include it in a web page, like so:

ng-init is a directive that initializes application data by assigning values to variables. We can put it right after the ng-app tag, like so:

We have defined 2 variables, the first an object with key-value pairs, and another an array of such objects.

This basically means that this particular div element, as well as all the elements inside it, are going to be the View. ng-controller is the application controller, which is an object.
By ng-controller=”” we are defining the controller.
So far we have:

We are going to use the $scope element to provide data to our View. We’re going to use our controller to connect the two.

1

https://blogeduonix-2f3a.kxcdn.com/wp-content/uploads/2015/10/Learn-Javascript-And-JQuery-From-Scratch.png

Explanation: We are defining the firstA application, and then the application controller. We’re referencing the controller’s name inside the brackets(the same name we gave it in the HTML).
Inside the controller function, which is called a factory function, $scope links our HTML elements to variables in our function. We defined 2 variables, $scope.firstN and $scope.secondN and gave them initial values. We then defined a function for the $scope object, which multiplies our first variable by our second variable and returns the result. The ‘+’ in front of the variables inside the brackets converts string to integer. So, here we have a variable (multy) which is also a function.
We are now going back to the HTML and defining two elements which would be bound to our controller data, using ng-model to make the connection. Like so:

We got the value of $scope.multy to display in our HTML by using the expression {{multy()}}
When a user enters values in the text fields, the result will be automatically generated and displayed  to them.

In summary, we’ve shown how Angular controllers can be used to manage the data of Angular applications. A controller is defined in the HTML using the ng-controller attribute. The controller function creates variables which belong to the $scope object. As we have seen in the example, the controller can have a method as a variable (multy() in our example).
The controller (or $scope) variables are connected to the View using the ng-model attribute.

LEAVE A REPLY

Please enter your comment!
Please enter your name here