01/10/2018, 15:31

Bài 4: AngularJS – Expressions

Expression được sử dụng để buộc dữ liệu ứng dụng tới html. Expression được ghi bên trong 2 dấu ngoặc móc {{ express }}. Expression có cùng cách làm việc như ng-bind directives. Expression trong AngularJS là một biểu thức javascript và đưa ra dữ liệu nơi chúng được sử dụng. Sử dụng số ...

Expression được sử dụng để buộc dữ liệu ứng dụng tới html. Expression được ghi bên trong 2 dấu ngoặc móc {{ express }}. Expression có cùng cách làm việc như ng-bind directives.

Expression trong AngularJS là một biểu thức javascript và đưa ra dữ liệu nơi chúng được sử dụng.

Sử dụng số

<p> Chi phí quyển sách: {{cost * quantity}} $ </p>

Sử dụng chuỗi

<p> Hello {{firstname + “ “ + lastname}}!</p>

Sử dụng đối tượng

<p>ID: {{student.id}}</p>

Sử dụng mãng

<p>Mark(match): {{mark[3]}}</p>

EX: tạo một file với tên expressionAngularJS.htm với nội dung sau:

<html>

   <head>

<script src = “http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”></script>

      <title>AngularJS Expressions</title>

   </head>

   <body>

      <h1>Sample Application</h1>

      <div ng-app = “” ng-init = “quantity = 1;cost = 30; student = {firstname:’Tin’,lastname:’Ku’,id:101};marks = [80,90,75,73,60]”>

         <p>Hello {{student.firstname + ” ” + student.lastname}}!</p>

         <p>Expense on Books : {{cost * quantity}} $</p>

         <p>ID: {{student.id}}</p>

         <p>Marks(Math): {{marks[3]}}</p>

      </div>     

   </body>

</html>

Viết theo ng-bind:

<html>

   <head>

<script src = “http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”></script>

      <title>AngularJS Expressions</title>

   </head>

   <body>

      <h1>Sample Application</h1>

      <div ng-app = “” ng-init = “quantity = 1;cost = 30; student = {firstname:’Tin’,lastname:’Ku’,id:101};marks = [80,90,75,73,60]”>

         <p>Hello <span ng-bind=”student.firstname + ‘ ‘ + student.lastname”></span>!</p>

         <p>Expense on Books : <span ng-bind=”cost * quantity”></span> $</p>

         <p>ID: <span ng-bind=”student.id”></span></p>

         <p>Marks(Math): <span ng-bind=”marks[3]”></span></p>

      </div>     

   </body>

</html>

Hãy chạy thử và xem kết quả để trãi nghiệm.

So sánh giữa biểu thức AngularJS và Javascript

  • Giống như biểu thức Javascript, AngularJS có thể chứa đựng chuổi, toán tử, và biến.
  • Không giống như Javascript, biểu thức AngularJS có thể ghi bên trong HTML.
  • AngularJS expression không hổ trợ điều kiện, lặp, và xử lý ngoại lệ, trong khi Javascript làm được điều này.
  • AngularJS expression hổ trợ filter, còn Javascript thì không.
0