دوره آموزشی AngularJS به زبان فارسی - بخش شانزدهم
بسم الله الرحمن الرحیم
این دوره آموزشی تا بخش بیست و دوم مقدماتی خواهد بود اگر به این مطالب تسلط دارید لطفا به آموزش "طراحی یک Single Page Application با ASP.NET Web API و Angular.js " مراجعه کنید.
مشاهده تمامی آموزش های دوره AngularJS
آموزش AngularJS
بخش شانزدهم
AngularJS Ajax
AngularJS با استفاده از سرویس http$ امکان خواندن اطلاعات را از سرور فراهم می کند. سرور شما می تواند یک دیتابیس برای خواندن اطلاعات ایجاد کند. AngularJS به داده ها در قالب JSON نیاز دارد و هنگامی که داده ها آماده باشند سرویس http$ می تواند از داده های سرور به صورت زیر استفاده کنند.
function studentController($scope,$http) {
var url="data.txt";
$http.get(url).success( function(response) {
$scope.students = response;
});
}
در اینجا data.txt یک فایل است که شامل رکوردهایی برای دانش آموزان است. سرویس http$ یک فراخوانی به روش AJAX ایجاد می کند و فرایند بازیابی اطلاعات برای پرارپرتی های Model دانش آموزان را فراهم می کند. "students" model برای نمایش اطلاعات مورد استفاده قرار می گیرد.
مثال:
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.htm
<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).success( function(response) {
$scope.students = response;
});
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>
برای اجرا این مثال شما نیاز به یک وب سرور دارید. می توانید از ویژوال استادیو استفاده کنید و فایل HTML خود را در ویژوال استادیو باز کنید و سپس View in Browser را انتخاب کنید تا خروجی شما مشابه زیر شود.