集腋成裘-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会检测这个模板是否被浏览器加载或者加载多次并 ...
随机推荐
- php编程 之 php基础一
1,语法 PHP 脚本在服务器上执行,然后将纯 HTML 结果发送回浏览器.PHP 文件通常包含 HTML 标签和一些 PHP 脚本代码 比如下面这个:这是一个简单的 PHP 文件实例,它可以向浏览器 ...
- shell编程 之 输入输出重定向
1 输入输出重定向 标准输入:从终端得到命令,对于计算机来说,是从终端获得了命令,执行完了以后,结果和执行状态或者错误提示又会发回终端,这叫标准输出. 输入输出重定向就是从终端以外的别的地方得到输入, ...
- [机器学习] k近邻算法
算是机器学习中最简单的算法了,顾名思义是看k个近邻的类别,测试点的类别判断为k近邻里某一类点最多的,少数服从多数,要点摘录: 1. 关键参数:k值 && 距离计算方式 &&am ...
- 在Linux安装ASP.NET Core运行时环境
我使用的是Centos7 ,其它的Linux请参考微软文档 微软官方介绍文档: https://www.microsoft.com/n ...
- python中的多重循环
列表中会经常用到多重循环. if __name__=='__main__': names = ['xiaoming','wangwu','lisi'] ages = ['] for name,age ...
- 虚拟机安装CentOS配置静态IP
在VMware中安装Linux虚拟机后(比如CentOS6.*),不能访问网络,需要配置静态IP.虚拟机中推荐使用NET模式进行网络连接,在虚拟机的工具栏点击编辑>虚拟网络编辑器>NET模 ...
- python hmac解密
import hmac def get_singa_true(timestamp): sha1 = hmac.new("d1b964811afb40118a12068ff74a12f4&qu ...
- centos6.9安装crontab
yum install vixie-cron crontabs //安装 chkconfig crond on //开机自启动 service crond start //启动 然后就是执行 cron ...
- Python学习前期准备---第九天
一.Linux基础 - 计算机以及日后我们开发的程序防止的服务器的简单操作 二.Python开发 http://www.cnblogs.com/wupeiqi/articles/5433893.htm ...
- 007_zkCli.sh
一. [zk: localhost:2181(CONNECTED) 1] rmr /zkTestPaths_92018-06-25 11:18:30,189 [myid:] - WARN [main- ...