Angularjs-ajax

提供:Dev Guides
移動先:案内検索

AngularJS-Ajax

AngularJSは、サーバーからデータを読み取るサービスとして機能する$ httpコントロールを提供します。 サーバーは、目的のレコードを取得するためにデータベース呼び出しを行います。 AngularJSにはJSON形式のデータが必要です。 データの準備ができたら、次の方法で$ httpを使用してサーバーからデータを取得できます-

function studentController($scope,$https:) {
   var url = "data.txt";

   $https:.get(url).success( function(response) {
      $scope.students = response;
   });
}

ここで、ファイルdata.txtには学生レコードが含まれています。 $ httpサービスはajax呼び出しを行い、プロパティの学生に応答を設定します。 学生モデルを使用して、HTMLで表を描画できます。

data.txt

[
   {
      "Name" : "Mahesh Parashar",
      "RollNo" : 101,
      "Percentage" : "80%"
   },
   {
      "Name" : "Dinkar Kad",
      "RollNo" : 201,
      "Percentage" : "70%"
   },
   {
      "Name" : "Robert",
      "RollNo" : 191,
      "Percentage" : "75%"
   },
   {
      "Name" : "Julian Joe",
      "RollNo" : 111,
      "Percentage" : "77%"
   }
]

testAngularJS

<html>
   <head>
      <title>Angular JS Includes</title>

      <style>
         table, th , td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
         }
         table tr:nth-child(odd) {
            background-color: #f2f2f2;
         }
         table tr:nth-child(even) {
            background-color: #ffffff;
         }
      </style>
   </head>

   <body>
      <h2>AngularJS Sample Application</h2>
      <div ng-app = "" ng-controller = "studentController">

         <table>
            <tr>
               <th>Name</th>
               <th>Roll No</th>
               <th>Percentage</th>
            </tr>

            <tr ng-repeat = "student in students">
               <td>{{ student.Name }}</td>
               <td>{{ student.RollNo }}</td>
               <td>{{ student.Percentage }}</td>
            </tr>
         </table>
      </div>

      <script>
         function studentController($scope,$http) {
            var url = "/data.txt";

            $http.get(url).then( function(response) {
               $scope.students = response.data;
            });
         }
      </script>

      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
      </script>

   </body>
</html>

出力

この例を実行するには、_testAngularJS_および_data.txt_ファイルをWebサーバーにデプロイする必要があります。 WebブラウザーでサーバーのURLを使用して_testAngularJS_ファイルを開き、結果を確認します。