集腋成裘-05-angularJS -初识angular
私以为angular的最大特点是:只关注数据
1.1 angular之:双向绑定
<!DOCTYPE html>
<html ng-app="">
<head>
<meta charset="UTF-8">
<title>双向绑定</title>
<script src="../js/angular.js"></script>
<script type="text/javascript"> </script>
</head>
<body>
<div ng-app="">
<input type="text" ng-model="str">
<input type="text" ng-model="str">
</div> </body>
</html>
双向绑定-Code
既可以输入,同时还是输出.大致原理也可以理解,设置一个变量,每次修改文本框的值给变量重新赋值.然后变量值修改以后,给页面上绑定该变量的元素重新赋值显示.
1.2 angular之:模板
模板在angular中有ng-module与{{}}常用.注意使用{{}},由于页面加载可能会出现闪烁现象,可以通过添加ng-cloak解决
<!DOCTYPE html>
<html ng-app="">
<head>
<meta charset="UTF-8">
<title>双向绑定</title>
<script src="../js/angular.js"></script>
<script type="text/javascript"> </script>
</head>
<body>
<div ng-app="">
<input type="text" ng-model="a">
*
<input type="text" ng-model="b">
=
<span>{{a}}*{{b}}={{a*b}}</span>
</div> </body>
</html>
模板-Code
1.3 angular之:列表
在列表中显示中常用的是ng-repeat
<!DOCTYPE html>
<html ng-app="">
<head>
<meta charset="UTF-8">
<title>双向绑定</title>
<script src="../js/angular.js"></script>
<script type="text/javascript"> </script>
</head>
<body>
<div ng-init="arr=[1,53,654,12,5]">
<ul><li ng-repeat="item in arr">{{item}}</li></ul>
</div>
</body>
</html>
循环数组
<!DOCTYPE html>
<html ng-app="">
<head>
<meta charset="UTF-8">
<title>双向绑定</title>
<script src="../js/angular.js"></script>
<script type="text/javascript"> </script>
</head>
<body>
<div ng-init="users=[{name:'张三',age:20},{name:'李四',age:40}]">
<ul><li ng-repeat="item in users">姓名: {{item.name}} 年龄: {{item.age}}</li></ul>
</div>
</body>
</html>
循环json
下拉框
<div class="form-group">
<label class="col-sm-2 control-label">设备类型<span style="color:#f00">*</span></label>
<div class="col-sm-10">
<select class="form-control m-b" name="account" ng-model="UpdateObj.EquipmentType" datatype="s" nullmsg="请选择一项设备类型!">
<option value="">--请选择--</option>
<option ng-repeat='MT in EquipmentTypeList' value="{{MT.DictionaryCode}}">{{MT.DictionaryName}}</option>
</select>
</div>
</div>
下拉框
1.4 angular之:控制器
controller作用存放代码,将angular与JavaScript互通
<!DOCTYPE html>
<html ng-app="test">
<head>
<meta charset="UTF-8">
<title>controller测试</title>
<script src="../js/angular.js"></script>
<script type="text/javascript">
var app = angular.module("test",[]);
app.controller("firstContr",function($scope){
$scope.a=;
$scope.alert=function(s){
window.alert(s);
}
})
</script>
</head>
<body>
<div ng-controller="firstContr">
<input type="text" >
<input type="button" value="弹框" ng-click="(alert(a))">
</div>
</body>
</html>
controller测试
1.5 angular之:依赖注入
简单的说,函数的参数有定义方决定
1.6 angular之:过滤器
关键字是filter
<!DOCTYPE html>
<html ng-app="test">
<head>
<meta charset="UTF-8">
<title>过滤器</title>
<script src="../js/angular.js"></script>
<script type="text/javascript">
var app = angular.module("test",[]);
app.controller("firstContr",function($scope){
$scope.items=[{name:'商品 1',price:,time:},{name:'商品 2',price:,time:}]; $scope.alert=function(s){
window.alert(s);
}
})
</script>
</head>
<body>
<div ng-controller="firstContr">
<ul><li ng-repeat="item in items">
<h3>{{item.name}}</h3>
<span>{{item.price|currency}}</span>
<i>{{item.time|date:"yyyy-MM-dd"}}</i>
</li></ul>
</div>
</body>
</html>
过滤器
1.6.2
<!DOCTYPE html>
<html ng-app="test">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="../Scripts/angular.min.js?version=<%=VersionNo%>" "></script>
<script src="../Scripts/angular-route.min.js"></script> <script>
var app = angular.module('test', []);
app.controller('cont1', function ($scope,$timeout) {
$scope.items = [{ name: '张三', age: }, { name: '李四', age: }, { name: '王五', age: }];
});
</script>
</head>
<body>
<div ng-controller="cont1">
<ul>
<li>
{{items|filter:{age:} }}
</li>
</ul>
</div>
</body>
</html>
注意{age:16} 后面有个空格
1.6.3 过滤器排序
<!DOCTYPE html>
<html ng-app="test">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="../Scripts/angular.min.js?version=<%=VersionNo%>" "></script>
<script src="../Scripts/angular-route.min.js"></script> <script>
var app = angular.module('test', []);
app.controller('cont1', function ($scope,$timeout) {
$scope.items = [{ name: '张三', age: }, { name: '李四', age: }, { name: '王五', age: }];
});
</script>
</head>
<body>
<div ng-controller="cont1">
<ul>
<li>
{{items|orderBy:'age':true }}
</li>
</ul>
</div>
</body>
</html>
排序
1.7angular之:数据交互
常用的是$http,
1.7.1:get请求
$http.get(url,参数);
实验,用.net简单做一个测试
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace AngularTest
{
/// <summary>
/// Calculate 的摘要说明
/// </summary>
public class Calculate : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string a = context.Request["a"];
string b = context.Request["b"];
context.Response.Write("a="+a+"b="+b);
} public bool IsReusable
{
get
{
return false;
}
}
}
}
Calculate.ashx文件
<!DOCTYPE html>
<html ng-app="test">
<head>
<meta charset="UTF-8">
<title>数据交互</title>
<script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("test", []);
app.controller("firstContr", function ($scope, $http) {
$http.get('Calculate.ashx', {
params: { a: , b: }
}).success(function (res) { alert(res); }).
error(function () { alert('失败了') }); })
</script>
</head>
<body>
<div ng-controller="firstContr"> </div>
</body>
</html>
DataIn.html
2.0 初露锋芒
环境:sql数据库,C#语言 资料地址:https://pan.baidu.com/s/11x-xfqeDw_PIYZnDN4fAdg
<!doctype html>
<html ng-app="zns_weibo">
<head>
<meta charset="utf-8">
<title>智能课堂 —— 微博ajax接口测试 - www.zhinengshe.com</title>
<link href="style/weibo.css" rel="stylesheet" type="text/css" />
<script src="js/angular.js"></script>
<script>
var app = angular.module('zns_weibo', []); app.controller('weibo', function ($scope, $http) {
$scope.replies = [{ id: , content: "试试", time: , acc: , ref: }, { id: , content: "上的二二", time: , acc: , ref: }, { id: , content: "独特热特特认为他", time: , acc: , ref: }];
});
</script>
</head> <body ng-controller="weibo">
<div class="znsArea">
<!--留言-->
<div class="takeComment">
<textarea name="textarea" class="takeTextField" id="tijiaoText"></textarea>
<div class="takeSbmComment">
<input type="button" class="inputs" value="" />
<span>(可按 Enter 回复)</span>
</div>
</div>
<!--已留-->
<div class="commentOn">
<div class="noContent">暂无留言</div>
<div class="messList">
<div class="reply" ng-repeat="reply in replies">
<p class="replyContent">{{reply.content}}</p>
<p class="operation">
<span class="replyTime">{{reply.time*|date:"yyyy-MM-dd HH:mm:ss"}}</span>
<span class="handle">
<a href="javascript:;" class="top">{{reply.acc}}</a>
<a href="javascript:;" class="down_icon">{{reply.ref}}</a>
<a href="javascript:;" class="cut">删除</a>
</span>
</p>
</div>
</div>
<div class="page">
<a href="javascript:;" class="active"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
</div>
</div>
</div>
</body>
</html>
原始html
2.1 显示留言
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web; namespace AngularTest
{
/// <summary>
/// WeiBo 的摘要说明
/// </summary>
public class WeiBo : IHttpHandler
{
private string ConnStr = GetConnStr(); public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain"; string act = context.Request["act"];
switch (act)
{
case "add":
addInfo();
break;
case "get_page_count":
getCount();
break;
case "get":
string pageSize = context.Request["pageSize"];
string pageIndex = context.Request["pageIndex"];
int pageSizeI = ;
int pageIndexI =;
int.TryParse(pageSize, out pageSizeI);
int.TryParse(pageIndex, out pageIndexI);
string infos = "result:\\{"+ getInfo(pageIndexI, pageSizeI);
context.Response.Write(infos);
break;
case "acc":
acc();
break;
case "ref":
makeRef();
break;
case "del": if (del())
{
context.Response.Write("删除成功");
}
else
{
context.Response.Write("删除成功");
}
break;
} } private bool del(int id)
{
string sqlStr = string.Format("delete from [dbo].[weibo] where id= ({0})", id);
using (SqlConnection conn = new SqlConnection(ConnStr))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = sqlStr; if (cmd.ExecuteNonQuery() > )
{
return true;//表示删除成功
}
else
{
return false;//表示删除失败
}
}
} } private void makeRef()
{
throw new NotImplementedException();
} private void acc()
{
throw new NotImplementedException();
} private string getInfo(int page, int pageSize)
{
StringBuilder sb = new StringBuilder();
sb.Append("");
if (page < ) { page = ; }
if (pageSize<)
{
pageSize = ;
}
string sqlStr = string.Format(@" select * from (select * ,ROW_NUMBER() over (Order by id desc) as rowNumber from weibo ) as temp
where temp.rowNumber between ({1}*({0}-1)+1) and ({0}*{1})", page, pageSize);
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlStr, ConnStr))
{
DataTable dt = new DataTable();
adapter.Fill(dt); if (dt != null && dt.Rows.Count > )
{
int count = dt.Rows.Count; for (int i = ; i < count; i++)
{
if (i == count - )
{
sb.Append(" {\"id\": \""+dt.Rows[i]["ID"]+"\", \"content\": \""+dt.Rows[i]["contents"]+"\", \"time\": \""+dt.Rows[i]["time"]+"\", \"acc\": \""+dt.Rows[i]["acc"]+"\", \"ref\": \""+dt.Rows[i]["ref"]+"\"}");
}
else {
//简单起见,如果有多个,添加分割符,
sb.Append(" {\"id\": \"" + dt.Rows[i]["ID"] + "\", \"content\": \"" + dt.Rows[i]["contents"] + "\", \"time\": \"" + dt.Rows[i]["time"] + "\", \"acc\": \"" + dt.Rows[i]["acc"] + "\", \"ref\": \"" + dt.Rows[i]["ref"] + "\"}" + "@#$%");
}
} }
}
return sb.ToString(); } private void getCount()
{
throw new NotImplementedException();
} public static string GetConnStr()
{
return ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
}
public bool IsReusable
{
get
{
return false;
}
}
private void addInfo()
{
throw new NotImplementedException();
}
}
}
getInfo()
<!doctype html>
<html ng-app="zns_weibo">
<head>
<meta charset="utf-8">
<title>智能课堂 —— 微博ajax接口测试 - www.zhinengshe.com</title>
<link href="style/weibo.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
<script src="js/jquery.js"></script>
<script>
var app = angular.module('zns_weibo', []); app.controller('weibo', function ($scope, $http) {
$scope.replies = []; //定义一个函数,用于将后台的json字符串数据转化为json数组
//1:后台直接传{开头有问题;2:split先这样吧,把流程跑通
$scope.behindChangeJsonArray = function (strResult) {
strResult = strResult.replace("result:\\{", "");
var strArray = strResult.split("@#$%");
var jsonArray = [];
for (var i = ; i < strArray.length; i++) {
var obj = angular.fromJson(strArray[i]);
jsonArray.push(obj);
}
return jsonArray;
}; //显示留言
$http.get('weibo.ashx', {
params: { act: 'get', pageSize: ,pageIndex: }
}).success(function (strResult) {
$scope.replies = $scope.behindChangeJsonArray(strResult);
}).error(function () {
alert('错误');
}); });
</script>
</head> <body ng-controller="weibo">
<div class="znsArea">
<!--留言-->
<div class="takeComment">
<textarea name="textarea" class="takeTextField" id="tijiaoText"></textarea>
<div class="takeSbmComment">
<input type="button" class="inputs" value="" />
<span>(可按 Enter 回复)</span>
</div>
</div>
<!--已留-->
<div class="commentOn">
<div class="noContent">暂无留言</div>
<div class="messList">
<div class="reply" ng-repeat="reply in replies">
<p class="replyContent">{{reply.content}} </p>
<p class="operation">
<span class="replyTime">{{reply.time*|date:"yyyy-MM-dd HH:mm:ss"}}</span>
<span class="handle">
<a href="javascript:;" class="top">{{reply.acc}}</a>
<a href="javascript:;" class="down_icon">{{reply.ref}}</a>
<a href="javascript:;" class="cut">删除</a>
</span>
</p>
</div>
</div>
<div class="page">
<a href="javascript:;" class="active"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
</div>
</div>
</div>
</body>
</html>
注意 //显示留言 方法
2.2 提交留言
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web; namespace AngularTest
{
/// <summary>
/// WeiBo 的摘要说明
/// </summary>
public class WeiBo : IHttpHandler
{
private string ConnStr = GetConnStr(); public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain"; string act = context.Request["act"];
switch (act)
{
case "add":
string contents = context.Request["contents"];
//当然为了添加成功以后,把该评论对应的添加时间 和ID 返回给前台
string ID = "";
string addTime = "";
if (addInfo(contents, out ID, out addTime))
{
//如果添加成功,返回
//返回:{error:0, id: 新添加内容的ID, time: 添加时间}
string result = "result:\\{"+"{\"error\": \"0\", \"id\": \"" + ID + "\", \"time\": \"" + addTime + "\"}";
context.Response.Write(result);
}
else {
string result = "result:\\{" + "{\"error\": 1}";
context.Response.Write(result);
} break;
case "get_page_count":
getCount();
break;
case "get":
string pageSize = context.Request["pageSize"];
string pageIndex = context.Request["pageIndex"];
int pageSizeI = ;
int pageIndexI = ;
int.TryParse(pageSize, out pageSizeI);
int.TryParse(pageIndex, out pageIndexI);
string infos = "result:\\{" + getInfo(pageIndexI, pageSizeI);
context.Response.Write(infos);
break;
case "acc":
acc();
break;
case "ref":
makeRef();
break;
case "del": if (del())
{
context.Response.Write("删除成功");
}
else
{
context.Response.Write("删除成功");
}
break;
} } private bool del(int id)
{
string sqlStr = string.Format("delete from [dbo].[weibo] where id= ({0})", id);
using (SqlConnection conn = new SqlConnection(ConnStr))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = sqlStr; if (cmd.ExecuteNonQuery() > )
{
return true;//表示删除成功
}
else
{
return false;//表示删除失败
}
}
} } private void makeRef()
{
throw new NotImplementedException();
} private void acc()
{
throw new NotImplementedException();
} private string getInfo(int page, int pageSize)
{
StringBuilder sb = new StringBuilder();
sb.Append("");
if (page < ) { page = ; }
if (pageSize < )
{
pageSize = ;
}
string sqlStr = string.Format(@" select * from (select * ,ROW_NUMBER() over (Order by id desc) as rowNumber from weibo ) as temp
where temp.rowNumber between ({1}*({0}-1)+1) and ({0}*{1})", page, pageSize);
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlStr, ConnStr))
{
DataTable dt = new DataTable();
adapter.Fill(dt); if (dt != null && dt.Rows.Count > )
{
int count = dt.Rows.Count; for (int i = ; i < count; i++)
{
if (i == count - )
{
sb.Append(" {\"id\": \"" + dt.Rows[i]["ID"] + "\", \"content\": \"" + dt.Rows[i]["contents"] + "\", \"time\": \"" + dt.Rows[i]["time"] + "\", \"acc\": \"" + dt.Rows[i]["acc"] + "\", \"ref\": \"" + dt.Rows[i]["ref"] + "\"}");
}
else
{
//简单起见,如果有多个,添加分割符,
sb.Append(" {\"id\": \"" + dt.Rows[i]["ID"] + "\", \"content\": \"" + dt.Rows[i]["contents"] + "\", \"time\": \"" + dt.Rows[i]["time"] + "\", \"acc\": \"" + dt.Rows[i]["acc"] + "\", \"ref\": \"" + dt.Rows[i]["ref"] + "\"}" + "@#$%");
}
} }
}
return sb.ToString(); } private void getCount()
{
throw new NotImplementedException();
} public static string GetConnStr()
{
return ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
}
public bool IsReusable
{
get
{
return false;
}
}
private bool addInfo(string contents, out string ID, out string addTime)
{
ID = "";
addTime = "";
bool result = false;
long currentTicks = DateTime.Now.Ticks;
DateTime dtFrom = new DateTime(, , , , , , );
long currentMillis = (currentTicks - dtFrom.Ticks) / / ;
string sqlStr = string.Format("insert into [dbo].[weibo] (contents, time, acc, ref) values('{0}',{1},0,0)", contents, currentMillis);
using (SqlConnection conn = new SqlConnection(ConnStr))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = sqlStr; try
{
if (cmd.ExecuteNonQuery() > )
{
//如果添加成功,获取id
string sqlStr2 = string.Format("select max(ID) from [dbo].[weibo] ");
cmd.CommandText = sqlStr2;
object maxID = cmd.ExecuteScalar();
if (maxID!=null)
{
ID = maxID.ToString();
}
addTime = currentMillis.ToString();
return true;//表示添加成功
}
else
{
return false;//表示添加失败
}
}
catch (Exception)
{ throw;
} }
} return result;
}
}
}
addInfo()
<!doctype html>
<html ng-app="zns_weibo">
<head>
<meta charset="utf-8">
<title>智能课堂 —— 微博ajax接口测试 - www.zhinengshe.com</title>
<link href="style/weibo.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
<script src="js/jquery.js"></script>
<script>
var app = angular.module('zns_weibo', []); app.controller('weibo', function ($scope, $http) {
$scope.replies = []; //定义一个函数,用于将后台的json字符串数据转化为json数组
//1:后台直接传{开头有问题;2:split先这样吧,把流程跑通
$scope.behindChangeJsonArray = function (strResult) {
strResult = strResult.replace("result:\\{", "");
var strArray = strResult.split("@#$%");
var jsonArray = [];
for (var i = ; i < strArray.length; i++) {
var obj = angular.fromJson(strArray[i]);
jsonArray.push(obj);
}
return jsonArray;
}; //显示留言
$http.get('weibo.ashx', {
params: { act: 'get', pageSize: , pageIndex: }
}).success(function (strResult) {
$scope.replies = $scope.behindChangeJsonArray(strResult);
}).error(function () {
alert('错误');
});
//提交留言
$scope.submitMsg = function () {
$http.get('weibo.ashx', {
params: {act: 'add', contents: $scope.inputText}
}).success(function (strResult) {
debugger;
var result = $scope.behindChangeJsonArray(strResult);
if (result != null && result[].error == ) {
//alert('成功了'); 刷新页面,通过unshift把最新的是数据放置在最上面
$scope.replies.unshift({
id: result[].ID,
content: $scope.inputText,
time: result[].time,
acc: ,
ref:
});
//确保每页最多显示6条
if ($scope.replies.length>) {
$scope.replies.pop();
}
//清空输入框内容
$scope.inputText = "";
} else {
alert('添加失败');
}
}).error(function () {
alert('错误');
});
} });
</script>
</head> <body ng-controller="weibo">
<div class="znsArea">
<!--留言-->
<div class="takeComment">
<textarea name="textarea" class="takeTextField" id="tijiaoText" ng-model="inputText"></textarea>
<div class="takeSbmComment">
<input type="button" class="inputs" value="" ng-click="submitMsg()" />
<span>(可按 Enter 回复)</span>
</div>
</div> <!--已留-->
<div class="commentOn">
<div class="noContent">暂无留言</div>
<div class="messList">
<div class="reply" ng-repeat="reply in replies">
<p class="replyContent">{{reply.content}} </p>
<p class="operation">
<span class="replyTime">{{reply.time*|date:"yyyy-MM-dd HH:mm:ss"}}</span>
<span class="handle">
<a href="javascript:;" class="top">{{reply.acc}}</a>
<a href="javascript:;" class="down_icon">{{reply.ref}}</a>
<a href="javascript:;" class="cut">删除</a>
</span>
</p>
</div>
</div>
<div class="page">
<a href="javascript:;" class="active"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
</div>
</div>
</div>
</body>
</html>
//提交留言
2.3 判断留言数据长度,决定"暂无留言"的显示与否
<div class="noContent" ng-show="replies.length==0">暂无留言</div>
2.4 页码条
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web; namespace AngularTest
{
/// <summary>
/// WeiBo 的摘要说明
/// </summary>
public class WeiBo : IHttpHandler
{
private string ConnStr = GetConnStr(); public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain"; string act = context.Request["act"];
string pageSize = context.Request["pageSize"];
int pageSizeI = ;
switch (act)
{
case "add":
string contents = context.Request["contents"];
//当然为了添加成功以后,把该评论对应的添加时间 和ID 返回给前台
string ID = "";
string addTime = "";
if (addInfo(contents, out ID, out addTime))
{
//如果添加成功,返回
//返回:{error:0, id: 新添加内容的ID, time: 添加时间}
string result = "result:\\{" + "{\"error\": \"0\", \"id\": \"" + ID + "\", \"time\": \"" + addTime + "\"}";
context.Response.Write(result);
}
else
{
string result = "result:\\{" + "{\"error\": 1}";
context.Response.Write(result);
} break;
case "get_page_count":
pageSize = context.Request["pageSize"];
int.TryParse(pageSize, out pageSizeI);
int pages = getCount(pageSizeI);
context.Response.Write(pages);
break;
case "get": string pageIndex = context.Request["pageIndex"]; int pageIndexI = ;
int.TryParse(pageSize, out pageSizeI);
int.TryParse(pageIndex, out pageIndexI);
string infos = "result:\\{" + getInfo(pageIndexI, pageSizeI);
context.Response.Write(infos);
break;
case "acc":
acc();
break;
case "ref":
makeRef();
break;
case "del": if (del())
{
context.Response.Write("删除成功");
}
else
{
context.Response.Write("删除成功");
}
break;
} } private bool del(int id)
{
string sqlStr = string.Format("delete from [dbo].[weibo] where id= ({0})", id);
using (SqlConnection conn = new SqlConnection(ConnStr))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = sqlStr; if (cmd.ExecuteNonQuery() > )
{
return true;//表示删除成功
}
else
{
return false;//表示删除失败
}
}
} } private void makeRef()
{
throw new NotImplementedException();
} private void acc()
{
throw new NotImplementedException();
} private string getInfo(int page, int pageSize)
{
StringBuilder sb = new StringBuilder();
sb.Append("");
if (page < ) { page = ; }
if (pageSize < )
{
pageSize = ;
}
string sqlStr = string.Format(@" select * from (select * ,ROW_NUMBER() over (Order by id desc) as rowNumber from weibo ) as temp
where temp.rowNumber between ({1}*({0}-1)+1) and ({0}*{1})", page, pageSize);
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlStr, ConnStr))
{
DataTable dt = new DataTable();
adapter.Fill(dt); if (dt != null && dt.Rows.Count > )
{
int count = dt.Rows.Count; for (int i = ; i < count; i++)
{
if (i == count - )
{
sb.Append(" {\"id\": \"" + dt.Rows[i]["ID"] + "\", \"content\": \"" + dt.Rows[i]["contents"] + "\", \"time\": \"" + dt.Rows[i]["time"] + "\", \"acc\": \"" + dt.Rows[i]["acc"] + "\", \"ref\": \"" + dt.Rows[i]["ref"] + "\"}");
}
else
{
//简单起见,如果有多个,添加分割符,
sb.Append(" {\"id\": \"" + dt.Rows[i]["ID"] + "\", \"content\": \"" + dt.Rows[i]["contents"] + "\", \"time\": \"" + dt.Rows[i]["time"] + "\", \"acc\": \"" + dt.Rows[i]["acc"] + "\", \"ref\": \"" + dt.Rows[i]["ref"] + "\"}" + "@#$%");
}
} }
}
return sb.ToString(); } private int getCount(int pageSizeI)
{
string sqlStr = string.Format("select count(1) from [dbo].[weibo] ");
using (SqlConnection conn = new SqlConnection(ConnStr))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = sqlStr; try
{
object maxID = cmd.ExecuteScalar(); if (maxID != null)
{
double count = ;
double.TryParse(maxID.ToString(), out count);
double pages = Math.Ceiling(count / pageSizeI);
return Convert.ToInt32(pages);
}
else
{
return ;
} }
catch (Exception)
{ throw;
} }
}
} public static string GetConnStr()
{
return ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
}
public bool IsReusable
{
get
{
return false;
}
}
private bool addInfo(string contents, out string ID, out string addTime)
{
ID = "";
addTime = "";
long currentTicks = DateTime.Now.Ticks;
DateTime dtFrom = new DateTime(, , , , , , );
long currentMillis = (currentTicks - dtFrom.Ticks) / / ;
string sqlStr = string.Format("insert into [dbo].[weibo] (contents, time, acc, ref) values('{0}',{1},0,0)", contents, currentMillis);
using (SqlConnection conn = new SqlConnection(ConnStr))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = sqlStr; try
{
if (cmd.ExecuteNonQuery() > )
{
//如果添加成功,获取id
string sqlStr2 = string.Format("select max(ID) from [dbo].[weibo] ");
cmd.CommandText = sqlStr2;
object maxID = cmd.ExecuteScalar();
if (maxID != null)
{
ID = maxID.ToString();
}
addTime = currentMillis.ToString();
return true;//表示添加成功
}
else
{
return false;//表示添加失败
}
}
catch (Exception)
{ throw;
} }
} }
}
}
getCount()
<!doctype html>
<html ng-app="zns_weibo">
<head>
<meta charset="utf-8">
<title>智能课堂 —— 微博ajax接口测试 - www.zhinengshe.com</title>
<link href="style/weibo.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
<script src="js/jquery.js"></script>
<script>
var app = angular.module('zns_weibo', []); app.controller('weibo', function ($scope, $http) {
$scope.replies = [];//定义评论信息
$scope.pages = [];//定义页码
$scope.curPage = ;//定义当前页码
$scope.pageSize = ;//定义每页包含的数目;一般通过后台配置或者webconfig
//定义一个函数,用于将后台的json字符串数据转化为json数组
//1:后台直接传{开头有问题;2:split先这样吧,把流程跑通
$scope.behindChangeJsonArray = function (strResult) {
strResult = strResult.replace("result:\\{", "");
var strArray = strResult.split("@#$%");
var jsonArray = [];
for (var i = ; i < strArray.length; i++) {
var obj = angular.fromJson(strArray[i]);
jsonArray.push(obj);
}
return jsonArray;
};
//将"显示留言"进行封装,因为页签切换的时候也要使用到
function getPage(p) {
//获取某页数据时候
$scope.curPage = p;
setCurrentPage($scope.pages.length);
//显示留言
$http.get('weibo.ashx', {
params: { act: 'get', pageSize: $scope.pageSize, pageIndex: p }
}).success(function (strResult) {
$scope.replies = $scope.behindChangeJsonArray(strResult);
}).error(function () {
alert('错误');
});
};
//默认显示第一页
getPage();
//将函数放到$scope上,方便ng-click使用
$scope.getPage = getPage;
//提交留言
$scope.submitMsg = function () {
$http.get('weibo.ashx', {
params: {act: 'add', contents: $scope.inputText}
}).success(function (strResult) {
debugger;
var result = $scope.behindChangeJsonArray(strResult);
if (result != null && result[].error == ) {
//alert('成功了'); 刷新页面,通过unshift把最新的是数据放置在最上面
$scope.replies.unshift({
id: result[].ID,
content: $scope.inputText,
time: result[].time,
acc: ,
ref:
});
//确保每页最多显示6条
if ($scope.replies.length>) {
$scope.replies.pop();
}
//清空输入框内容
$scope.inputText = "";
} else {
alert('添加失败');
}
}).error(function () {
alert('错误');
});
}
//页码--开始
function setCurrentPage(pages) {
$scope.pages = [];//先清空一下
for (var i = ; i <= pages; i++) {
if (i == $scope.curPage) {
$scope.pages.push({ num: i, className: 'active' });
} else {
$scope.pages.push({ num: i, className: '' });
}
}
}
$http.get('weibo.ashx', {
params: { act: 'get_page_count', pageSize: $scope.pageSize, }
}).success(function (result) {
setCurrentPage(result);
}).error(function () {
alert("错误")
});
//页码--结束
});
</script>
</head> <body ng-controller="weibo">
<div class="znsArea">
<!--留言-->
<div class="takeComment">
<textarea name="textarea" class="takeTextField" id="tijiaoText" ng-model="inputText"></textarea>
<div class="takeSbmComment">
<input type="button" class="inputs" value="" ng-click="submitMsg()" />
<span>(可按 Enter 回复)</span>
</div>
</div> <!--已留-->
<div class="commentOn">
<div class="noContent" ng-show="replies.length==0">暂无留言</div>
<div class="page">
<a href="javascript:;" ng-repeat="page in pages" class="{{page.className}}" ng-click="getPage(page.num)">{{page.num}}</a>
</div>
<div class="messList">
<div class="reply" ng-repeat="reply in replies">
<p class="replyContent">{{reply.content}} </p>
<p class="operation">
<span class="replyTime">{{reply.time*|date:"yyyy-MM-dd HH:mm:ss"}}</span>
<span class="handle">
<a href="javascript:;" class="top">{{reply.acc}}</a>
<a href="javascript:;" class="down_icon">{{reply.ref}}</a>
<a href="javascript:;" class="cut">删除</a>
</span>
</p>
</div>
</div> </div>
</div>
</body>
</html>
//页码
2.5 点赞
<!doctype html>
<html ng-app="zns_weibo">
<head>
<meta charset="utf-8">
<title>智能课堂 —— 微博ajax接口测试 - www.zhinengshe.com</title>
<link href="style/weibo.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
<script src="js/jquery.js"></script>
<script>
var app = angular.module('zns_weibo', []); app.controller('weibo', function ($scope, $http) {
$scope.replies = [];//定义评论信息
$scope.pages = [];//定义页码
$scope.curPage = ;//定义当前页码
$scope.pageSize = ;//定义每页包含的数目;一般通过后台配置或者webconfig
//定义一个函数,用于将后台的json字符串数据转化为json数组
//1:后台直接传{开头有问题;2:split先这样吧,把流程跑通
$scope.behindChangeJsonArray = function (strResult) {
strResult = strResult.replace("result:\\{", "");
var strArray = strResult.split("@#$%");
var jsonArray = [];
for (var i = ; i < strArray.length; i++) {
var obj = angular.fromJson(strArray[i]);
jsonArray.push(obj);
}
return jsonArray;
};
//将"显示留言"进行封装,因为页签切换的时候也要使用到
function getPage(p) {
//获取某页数据时候
$scope.curPage = p;
setCurrentPage($scope.pages.length);
//显示留言
$http.get('weibo.ashx', {
params: { act: 'get', pageSize: $scope.pageSize, pageIndex: p }
}).success(function (strResult) {
$scope.replies = $scope.behindChangeJsonArray(strResult);
}).error(function () {
alert('错误');
});
};
//默认显示第一页
getPage();
//将函数放到$scope上,方便ng-click使用
$scope.getPage = getPage;
//提交留言
$scope.submitMsg = function () {
$http.get('weibo.ashx', {
params: {act: 'add', contents: $scope.inputText}
}).success(function (strResult) {
debugger;
var result = $scope.behindChangeJsonArray(strResult);
if (result != null && result[].error == ) {
//alert('成功了'); 刷新页面,通过unshift把最新的是数据放置在最上面
$scope.replies.unshift({
id: result[].ID,
content: $scope.inputText,
time: result[].time,
acc: ,
ref:
});
//确保每页最多显示6条
if ($scope.replies.length>) {
$scope.replies.pop();
}
//清空输入框内容
$scope.inputText = "";
} else {
alert('添加失败');
}
}).error(function () {
alert('错误');
});
}
//页码--开始
function setCurrentPage(pages) {
$scope.pages = [];//先清空一下
for (var i = ; i <= pages; i++) {
if (i == $scope.curPage) {
$scope.pages.push({ num: i, className: 'active' });
} else {
$scope.pages.push({ num: i, className: '' });
}
}
}
$http.get('weibo.ashx', {
params: { act: 'get_page_count', pageSize: $scope.pageSize, }
}).success(function (result) {
setCurrentPage(result);
}).error(function () {
alert("错误")
});
//页码--结束 //点赞
$scope.fnAcc = function (id) {
//拿到id后,更新数据库
$http.get('weibo.ashx', {
params: { act: 'acc', id:id, }
}).success(function (result) {
alert(result);
//点完赞后刷新页面
getPage($scope.curPage); }).error(function () {
alert("错误")
});
};
//踩
$scope.fnRef = function (id) {
//拿到id后,更新数据库
$http.get('weibo.ashx', {
params: { act: 'ref', id: id, }
}).success(function (result) {
alert(result);
for (var i = ; i < $scope.replies.length; i++) {
if ($scope.replies[i].id == id) {
$scope.replies[i].ref++;
}
} }).error(function () {
alert("错误")
}); };
});
</script>
</head> <body ng-controller="weibo">
<div class="znsArea">
<!--留言-->
<div class="takeComment">
<textarea name="textarea" class="takeTextField" id="tijiaoText" ng-model="inputText"></textarea>
<div class="takeSbmComment">
<input type="button" class="inputs" value="" ng-click="submitMsg()" />
<span>(可按 Enter 回复)</span>
</div>
</div> <!--已留-->
<div class="commentOn">
<div class="noContent" ng-show="replies.length==0">暂无留言</div>
<div class="page">
<a href="javascript:;" ng-repeat="page in pages" class="{{page.className}}" ng-click="getPage(page.num)">{{page.num}}</a>
</div>
<div class="messList">
<div class="reply" ng-repeat="reply in replies">
<p class="replyContent">{{reply.content}} </p>
<p class="operation">
<span class="replyTime">{{reply.time*|date:"yyyy-MM-dd HH:mm:ss"}}</span>
<span class="handle">
<a href="javascript:;" class="top" ng-click="fnAcc(reply.id)">{{reply.acc}}</a>
<a href="javascript:;" class="down_icon" ng-click="fnRef(reply.id)">{{reply.ref}}</a>
<a href="javascript:;" class="cut">删除</a>
</span>
</p>
</div>
</div> </div>
</div>
</body>
</html>
acc()
<!doctype html>
<html ng-app="zns_weibo">
<head>
<meta charset="utf-8">
<title>智能课堂 —— 微博ajax接口测试 - www.zhinengshe.com</title>
<link href="style/weibo.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
<script src="js/jquery.js"></script>
<script>
var app = angular.module('zns_weibo', []); app.controller('weibo', function ($scope, $http) {
$scope.replies = [];//定义评论信息
$scope.pages = [];//定义页码
$scope.curPage = ;//定义当前页码
$scope.pageSize = ;//定义每页包含的数目;一般通过后台配置或者webconfig
//定义一个函数,用于将后台的json字符串数据转化为json数组
//1:后台直接传{开头有问题;2:split先这样吧,把流程跑通
$scope.behindChangeJsonArray = function (strResult) {
strResult = strResult.replace("result:\\{", "");
var strArray = strResult.split("@#$%");
var jsonArray = [];
for (var i = ; i < strArray.length; i++) {
var obj = angular.fromJson(strArray[i]);
jsonArray.push(obj);
}
return jsonArray;
};
//将"显示留言"进行封装,因为页签切换的时候也要使用到
function getPage(p) {
//获取某页数据时候
$scope.curPage = p;
setCurrentPage($scope.pages.length);
//显示留言
$http.get('weibo.ashx', {
params: { act: 'get', pageSize: $scope.pageSize, pageIndex: p }
}).success(function (strResult) {
$scope.replies = $scope.behindChangeJsonArray(strResult);
}).error(function () {
alert('错误');
});
};
//默认显示第一页
getPage();
//将函数放到$scope上,方便ng-click使用
$scope.getPage = getPage;
//提交留言
$scope.submitMsg = function () {
$http.get('weibo.ashx', {
params: {act: 'add', contents: $scope.inputText}
}).success(function (strResult) {
debugger;
var result = $scope.behindChangeJsonArray(strResult);
if (result != null && result[].error == ) {
//alert('成功了'); 刷新页面,通过unshift把最新的是数据放置在最上面
$scope.replies.unshift({
id: result[].ID,
content: $scope.inputText,
time: result[].time,
acc: ,
ref:
});
//确保每页最多显示6条
if ($scope.replies.length>) {
$scope.replies.pop();
}
//清空输入框内容
$scope.inputText = "";
} else {
alert('添加失败');
}
}).error(function () {
alert('错误');
});
}
//页码--开始
function setCurrentPage(pages) {
$scope.pages = [];//先清空一下
for (var i = ; i <= pages; i++) {
if (i == $scope.curPage) {
$scope.pages.push({ num: i, className: 'active' });
} else {
$scope.pages.push({ num: i, className: '' });
}
}
}
$http.get('weibo.ashx', {
params: { act: 'get_page_count', pageSize: $scope.pageSize, }
}).success(function (result) {
setCurrentPage(result);
}).error(function () {
alert("错误")
});
//页码--结束 //点赞
$scope.fnAcc = function (id) {
//拿到id后,更新数据库
$http.get('weibo.ashx', {
params: { act: 'acc', id:id, }
}).success(function (result) {
alert(result);
//点完赞后刷新页面
getPage($scope.curPage); }).error(function () {
alert("错误")
});
};
//踩
$scope.fnRef = function (id) {
//拿到id后,更新数据库
$http.get('weibo.ashx', {
params: { act: 'ref', id: id, }
}).success(function (result) {
alert(result);
for (var i = ; i < $scope.replies.length; i++) {
if ($scope.replies[i].id == id) {
$scope.replies[i].ref++;
}
} }).error(function () {
alert("错误")
}); };
});
</script>
</head> <body ng-controller="weibo">
<div class="znsArea">
<!--留言-->
<div class="takeComment">
<textarea name="textarea" class="takeTextField" id="tijiaoText" ng-model="inputText"></textarea>
<div class="takeSbmComment">
<input type="button" class="inputs" value="" ng-click="submitMsg()" />
<span>(可按 Enter 回复)</span>
</div>
</div> <!--已留-->
<div class="commentOn">
<div class="noContent" ng-show="replies.length==0">暂无留言</div>
<div class="page">
<a href="javascript:;" ng-repeat="page in pages" class="{{page.className}}" ng-click="getPage(page.num)">{{page.num}}</a>
</div>
<div class="messList">
<div class="reply" ng-repeat="reply in replies">
<p class="replyContent">{{reply.content}} </p>
<p class="operation">
<span class="replyTime">{{reply.time*|date:"yyyy-MM-dd HH:mm:ss"}}</span>
<span class="handle">
<a href="javascript:;" class="top" ng-click="fnAcc(reply.id)">{{reply.acc}}</a>
<a href="javascript:;" class="down_icon" ng-click="fnRef(reply.id)">{{reply.ref}}</a>
<a href="javascript:;" class="cut">删除</a>
</span>
</p>
</div>
</div> </div>
</div>
</body>
</html>
点赞
1.8 js中日期格式字符串加减N天
$scope.UpdateObj.PredepartureDate = $filter('jsonDate')($scope.UpdateObj.PredepartureDate, "yyyy-MM-dd");
$scope.UpdateObj.TravelDays = $scope.LineProductApplyList[i].TravelDays;
$scope.UpdateObj.PrebackDate = "/Date(" + new Date($scope.UpdateObj.PredepartureDate).setDate(new Date($scope.UpdateObj.PredepartureDate).getDate() + parseInt($scope.UpdateObj.TravelDays)) + ")/";
$scope.UpdateObj.PrebackDate = $filter('jsonDate')($scope.UpdateObj.PrebackDate, "yyyy-MM-dd");
集腋成裘-05-angularJS -初识angular的更多相关文章
- 升级 AngularJS 至 Angular
Victor Savkin 大神撰写了一系列文章详细介绍如何升级 AngularJS 应用: NgUpgrade in Depth Upgrade Shell Two Approaches to Up ...
- 初识Angular
一.AngularJs简介 1.AngularJS使用了不同的方法,它尝试去补足HTML本身在构建应用方面的缺陷.AngularJS通过使用我们称为标识符(directives)的结构,让浏览器能够识 ...
- 走进AngularJs(一)angular基本概念的认识与实战
一.前言 前端技术的发展是如此之快,各种优秀技术.优秀框架的出现简直让人目不暇接,作为一名业界新秀,紧跟时代潮流,学习掌握新知识自然是不敢怠慢.当听到AngularJs这个名字并知道是google在维 ...
- 夺命雷公狗—angularjs—25—angular内置的方法(高级)
查看版本信息 angular.version console.log(angular.version); 判断是否相等 angular.equals() var str1 = ''; var str2 ...
- AngularJS(17)-Angular小程序
现在可以开始创建您的第一个 AngularJS 应用程序,一个 AngularJS 单页 Web 应用. <!DOCTYPE html> <html lang="en&qu ...
- 初识 Angular 体会
一句话描述:一个前端的类似MVC框架的JS库 刚接触2天,刚一看感觉和asp.net mvc能实现的功能有点重复. 虽然asp.net的表单验证,Razor语法使其在前端开发有较大提升,但要实现比较高 ...
- AngularJS初识
AngularJS 简介 AngularJS是一个javaScript框架,是一个用JavaScript编写的库,通过指令扩展了HTML,且通过表达式绑定数据到HTML中. AngularJS使开发 ...
- angularjs初识ng-app、ng-model、ng-repeat指令
ng-app属性是angular.js的标志语句,它标记了angular.js的作用域.ng-app可以添加在很多地方,像上面那样添加到html标签上,说明angular脚本对整个页面都起作用.也可以 ...
- AngularJS方法 —— angular.bootstrap
描述: 此方法用于手动加载angularjs模板 (官方翻译:注意基于端到端的测试不能使用此功能来引导手动加载,他们必须使用ngapp. angularjs会检测这个模板是否被浏览器加载或者加载多次并 ...
随机推荐
- Open-Drain与Push-Pull【转】
转自:https://www.cnblogs.com/zhangpengshou/p/3643546.html GPIO的功能,简单说就是可以根据自己的需要去配置为输入或输出.(General Pur ...
- Python备份MySQL数据库【转】
#!/usr/bin/env python # coding: utf- import os import time ''' defined variable ''' databases=['hch' ...
- python3+selenium入门04-元素定位
我们在对浏览界面做操作时,比如点击按钮,搜索框输入内容.都需要把鼠标挪过去,然后再点击,或者输入内容.在selenium操作时也是一样的.需要先对元素进行定位,然后才能进行操作.可以借助浏览器的开发者 ...
- HBase详细概述
原文地址:https://blog.csdn.net/u010270403/article/details/51648462 本文首先简单介绍了HBase,然后重点讲述了HBase的高并发和实时处理数 ...
- redhat yum
背景 这个redhat可让我好一顿折腾,对于这个yum的安装,如果成功则罢,不成功可有的收拾的.还是centos比较好啊. 转载 1 下载下面四个软件包(可以从163下载,版本号自己搜索) wget ...
- centos如何安装Python3
Linux下默认系统自带python2.6的版本,这个版本被系统很多程序所依赖,所以不建议删除,如果使用最新的Python3那么我们知道编译安装源码包和系统默认包之间是没有任何影响的,所以可以安装py ...
- 所有ORM操作 (第二版)
####################################################################### # PUBLIC METHODS THAT ALTER ...
- Less常用知识点
上篇文章介绍了如何安装Less,我们将所有东西都写在.less里面,最后通过命令将.less转换成.css文件,就可以放入到项目里用了.今天了解一些less常用知识点. 1.变量:声明两个变量,一个是 ...
- 第一篇----mysql体系
mysql体系: 解释: 调用: 1.connectors:连接器 (远程调用mysql,Native很常用的mysql远程连接工具.其它是可以调用mysql支持的一些语言和方法) mysql结构 2 ...
- 30)django-ORM(元信息,级联删除,正反向操作,连表查询优化)
一:元信息 class User(models.Model): name=models.CharField(max_length,index=True) email=model.CharField(m ...