Controller component in AngularJS

An AngularJS application works primarily based on the controller component to control the flow of data in the application.

An AngularJS application works primarily based on the controller component to control the flow of data in the application. A controller is defined using the directive as the ng-controller . A controller is a JavaScript object that includes attributes and functions. Each controller accepts $ scope as a parameter to navigate to the application / module that this controller part controls.

  ng-app = "" ng-controller = "sinhvienController" > . 

Here is the bioControllerController part that uses the ng-controller directive. In the next steps, we will define the contentController as follows:

 

sinhvienController means that a JavaScript object with $ scope is a parameter.

  1. $ scope is directed to the application and is used by the sinhvienController object.
  2. $ scope.sinhvien is the attribute of the sinhvienController object.

cough and ten are two properties of $ scope.sinhvien object. We create values ​​for them (ho: Quan Tri, ten: Mang).

HoTen is a function of $ scope.sinhvien object whose task is to return the value of the student's full name.

In the HoTen function, we get the student object and then return the matching name.

Note, we can also define controller objects in separate JS files and declare in the HTML page.

Now we use the propertyController attribute with ng-model or expression as follows:

 Enter last name : < input type = "text" ng - model = "sinhvien.ho" > 
Enter the name : < input type = "text" ng - model = "sinhvien.ten" >

You entered : {{ sinhvien . HoTen ()}}
  1. We have attached the value of sinhvien.ho and sinhvien.ten to the 2 input boxes.
  2. We have attached the value of sinhvien.HoTen () to the HTML page.
  3. Now, every time we enter a ho or ten value into the input box, this student's full name will be automatically updated.

For example

Below is an example for the explanation of the controller above: thanhphanController.html

 Ví dụ về Controller Angular JS  src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js" > 

QTM application

  ng-app = "mainApp" ng-controller = " sinhvien Controller" > Nhập tên:  type = "text" ng-model = " sinhvien .ten" >

Nhập họ: type = "text" ng-model = " sinhvien .ho" >

Bạn đã nhập: {{sinhvien.HoTen()}}

When running the above code, we get the following result:

Controller component in AngularJS Picture 1Controller component in AngularJS Picture 1

Follow tutorialspoint

Previous post: Expression in AngularJS

Next article: HTML DOM element in AngularJS

5 ★ | 1 Vote