使用 AngularJS 连接到数据库






4.68/5 (18投票s)
如何使用 AngularJS 连接到数据库。
引言
AngularJS 围绕着一个信念构建:声明式编程应该用于构建用户界面和连接软件组件,而命令式编程非常适合表达业务逻辑。 该框架改编并扩展了传统的 HTML,通过双向数据绑定更好地服务于动态内容,从而可以自动同步模型和视图。 因此,AngularJS 降低了对 DOM 操作的强调,并提高了可测试性。
设计目标
- 将 DOM 操作与应用程序逻辑分离。 这提高了代码的可测试性。
- 将应用程序测试视为与应用程序编写同等重要。 测试难度受到代码结构方式的显着影响。
- 将应用程序的客户端与服务器端分离。 这允许开发工作并行进行,并允许双方重用。
- 指导开发人员完成构建应用程序的整个过程:从设计 UI,到编写业务逻辑,再到测试。
- 使常见任务变得简单,使困难任务成为可能。
Angular 遵循软件工程的 MVC 模式,并鼓励表示层、数据和逻辑组件之间的松散耦合。 使用依赖注入,Angular 将传统的服务器端服务(例如依赖于视图的控制器)引入客户端 Web 应用程序。 因此,后端的大部分负担得以减轻,从而使 Web 应用程序更轻便。
双向数据绑定
AngularJS 的双向数据绑定是其最显着的特性,它通过减轻服务器后端模板化职责来减少编写的代码量。 相反,模板根据模型中定义的作用域中的数据以纯 HTML 形式呈现。 Angular 中的 $scope
服务检测模型部分的变化,并通过控制器修改视图中的 HTML 表达式。 同样,对视图的任何更改都会反映在模型中。 这规避了主动操作 DOM 的需要,并鼓励 Web 应用程序的引导和快速原型设计。
一些 AngularJS 指令
AngularJS 指令允许开发人员指定自定义和可重用的 HTML 标签,这些标签控制某些元素的行为。
ng-app
将元素声明为应用程序的根元素,从而可以通过自定义 HTML 标签修改行为。
ng-bind
自动将 HTML 元素的文本更改为给定表达式的值。
ng-model
类似于
ng-bind
,但允许视图和作用域之间的双向数据绑定。ng-class
允许动态加载类属性。
ng-controller
指定一个 JavaScript 控制器类,用于评估 HTML 表达式。
ng-repeat
从集合中的每个项目实例化一个元素。
ng-show
&ng-hide
根据布尔表达式的值有条件地显示或隐藏元素。
ng-switch
根据选择表达式的值,有条件地从一组选择中实例化一个模板。
ng-view
负责处理在呈现由指定控制器驱动的模板之前解析 JSON 的路由的基本指令。
ngClick
ngClick
允许您在单击元素时指定自定义行为。ngSubmit
允许将 Angular 表达式绑定到
onsubmit
事件。ngHref
使用 Angular 标记(如在
href
属性中)如果用户在 Angular 有机会替换为实际 URL 之前单击该链接,则页面将打开到错误的 URL,链接将被破坏,并且很可能返回 404 错误。ngHref
指令解决了这个问题。
必备组件
- 安装 Visual Studio 2010 或 Visual Studio 2012
- 从 这里 下载 AngularJS
入门
要使用 AngularJS 与数据库通信,请创建一个 Web 服务并粘贴以下代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Services;
using System.Collections;
using System.Web.Script.Serialization;
namespace EmplyeeDetails
{
/// <summary>
/// Summary description for EmpService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script,
// using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class EmpService : System.Web.Services.WebService
{
string connection = @"Data Source=RAVINDRA\SQLEXPRESS;
Initial Catalog=Employee;Integrated Security=SSPI;";
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string InsertEmployee(string empID, string firstName,
string lastName, string address, string city,
string pincode, string state, string country)
{
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd;
try
{
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "INSERT INTO EmployeeDetails
(ID,FirstName,LastName,Address,City,Pincode,State,Country)
VALUES(@ID,@FirstName,@LastName,@Address,@City,@Pincode,@State,@COuntry)";
cmd.Parameters.AddWithValue("@ID", empID);
cmd.Parameters.AddWithValue("@FirstName", firstName);
cmd.Parameters.AddWithValue("@LastName", lastName);
cmd.Parameters.AddWithValue("@Address", address);
cmd.Parameters.AddWithValue("@City", city);
cmd.Parameters.AddWithValue("@Pincode", Convert.ToInt32(pincode));
cmd.Parameters.AddWithValue("@State", state);
cmd.Parameters.AddWithValue("@Country", country);
cmd.ExecuteNonQuery();
return "Record Inserted Successfully";
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
}
}
Script.js
将此代码粘贴到一个单独的 .js 文件中
$scope.save = function () {
$.ajax({
type: "POST",
url: "EmpService.asmx/InsertEmployee",
data: "{'empID':'" + $scope.EmpID + "','firstName':'" +
$scope.EmpFirstName + "','lastName':'" + $scope.EmpLastName + "',
'address':'" + $scope.EmpAddress + "','city':'" + $scope.EmpCity +
"','pincode':'" + $scope.EmpPincode + "','state':'" +
$scope.EmpState + "','country':'" + $scope.country + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
});
};
Employee.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="Employee.aspx.cs" Inherits="EmplyeeDetails.Employee" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app>
<head runat="server">
<title></title>
<script src="Scripts/angular.js"></script>
<script src="Scripts/jquery-1.8.3.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<form id="form1" ng-controller="EmpCtrl" ng-submit="save()">
<div style="text-align: center;">
<img alt="" src="banner-careers.jpg" />
</div>
<br />
<div style="font-family: Verdana; font-size: 12px; margin-left: 450px;">
<table>
<tr>
<td style="text-align: right;">Id :
</td>
<td>
<input type="text" id="txtEmpID" ng-model="EmpID" />
</td>
</tr>
<tr>
<td style="text-align: right;">First Name :
</td>
<td>
<input type="text" id="txtEmpFirstName" ng-model="EmpFirstName" />
</td>
</tr>
<tr>
<td style="text-align: right;">Last Name :
</td>
<td>
<input type="text" id="txtEmpLastName" ng-model="EmpLastName" />
</td>
</tr>
<tr>
<td style="text-align: right;">Address :
</td>
<td>
<textarea id="txtEmpAddress" cols="20" rows="2"
ng-model="EmpAddress"></textarea>
</td>
</tr>
<tr>
<td style="text-align: right;">City :
</td>
<td>
<input type="text" id="txtCity" ng-model="EmpCity" />
</td>
</tr>
<tr>
<td style="text-align: right;">Pin Code :
</td>
<td>
<input type="text" id="txtPinCode" ng-model="EmpPincode" />
</td>
</tr>
<tr>
<td style="text-align: right;">State :
</td>
<td>
<input type="text" id="txtState" ng-model="EmpState" />
</td>
</tr>
<tr>
<td style="text-align: right;">Country :
</td>
<td>
<input type="text" id="txtCountry" ng-model="country" />
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="submit" id="btnSubmit" value="Submit" />
</td>
</tr>
</table>
<div>
<input type="button" id="btnFetch" value="Fetch" ng-click="getEmployee()" />
</div>
</div>
<hr />
<table border="1" style="text-align: center; margin-left: 410px;">
<tr>
<td>ID
</td>
<td>First Name
</td>
<td>Last Name
</td>
<td>Address
</td>
<td>City
</td>
<td>Pincode
</td>
<td>State
</td>
<td>Country
</td>
</tr>
<tr>
<td>{{ID}}
</td>
<td>{{FirstName}}
</td>
<td>{{LastName}}
</td>
<td>{{Address}}
</td>
<td>{{City}}
</td>
<td>{{Pincode}}
</td>
<td>{{State}}
</td>
<td>{{Country}}
</td>
</tr>
</table>
</body>
</html>