集腋成裘-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=12;
            $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:10,time:1472565995363},{name:'商品 2',price:710,time:1472568995363}];

            $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: 16 }, { name: '李四', age: 26 }, { name: '王五', age: 16 }];
        });
    </script>
</head>
<body>
    <div ng-controller="cont1">
        <ul>
            <li>
                {{items|filter:{age:16} }}
            </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: 16 }, { name: '李四', age: 26 }, { name: '王五', age: 16 }];
        });
    </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: 12, b: 5 }
            }).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: 1, content: "试试", time: 1472568347, acc: 1, ref: 5 }, { id: 2, content: "上的二二", time: 1472568547, acc: 200, ref: 1 }, { id: 3, content: "独特热特特认为他", time: 1432568547, acc: 55, ref: 16 }];
        });
    </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*1000|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">1</a>
                <a href="javascript:;">2</a>
                <a href="javascript:;">3</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 = 5;
                    int pageIndexI =1;
                    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(1))
                    {
                        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() > 0)
                    {
                        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 < 1) { page = 1; }
            if (pageSize<1)
            {
                pageSize = 5;
            }
            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 > 0)
                {
                    int count = dt.Rows.Count;

                    for (int i = 0; i < count; i++)
                    {
                        if (i == count - 1)
                        {
                            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 = 0; i < strArray.length; i++) {
                    var obj = angular.fromJson(strArray[i]);
                    jsonArray.push(obj);
                }
                return jsonArray;
            };
             
            //显示留言
            $http.get('weibo.ashx', {
                params: { act: 'get', pageSize: 5,pageIndex:1 }
            }).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*1000|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">1</a>
                <a href="javascript:;">2</a>
                <a href="javascript:;">3</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 = 5;
                    int pageIndexI = 1;
                    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(1))
                    {
                        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() > 0)
                    {
                        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 < 1) { page = 1; }
            if (pageSize < 1)
            {
                pageSize = 5;
            }
            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 > 0)
                {
                    int count = dt.Rows.Count;

                    for (int i = 0; i < count; i++)
                    {
                        if (i == count - 1)
                        {
                            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(1970, 1, 1, 0, 0, 0, 0);
            long currentMillis = (currentTicks - dtFrom.Ticks) / 10000 / 1000;
            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() > 0)
                        {
                            //如果添加成功,获取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 = 0; i < strArray.length; i++) {
                    var obj = angular.fromJson(strArray[i]);
                    jsonArray.push(obj);
                }
                return jsonArray;
            };

            //显示留言
            $http.get('weibo.ashx', {
                params: { act: 'get', pageSize: 5, pageIndex: 1 }
            }).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[0].error == 0) {
                        //alert('成功了'); 刷新页面,通过unshift把最新的是数据放置在最上面
                        $scope.replies.unshift({
                            id: result[0].ID,
                            content: $scope.inputText,
                            time: result[0].time,
                            acc: 0,
                            ref: 0
                        });
                        //确保每页最多显示6条
                        if ($scope.replies.length>5) {
                            $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*1000|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">1</a>
                <a href="javascript:;">2</a>
                <a href="javascript:;">3</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 = 5;
            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 = 1;
                    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(1))
                    {
                        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() > 0)
                    {
                        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 < 1) { page = 1; }
            if (pageSize < 1)
            {
                pageSize = 5;
            }
            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 > 0)
                {
                    int count = dt.Rows.Count;

                    for (int i = 0; i < count; i++)
                    {
                        if (i == count - 1)
                        {
                            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 = 0;
                            double.TryParse(maxID.ToString(), out count);
                            double pages = Math.Ceiling(count / pageSizeI);
                            return Convert.ToInt32(pages);
                        }
                        else
                        {
                            return 0;
                        }

                    }
                    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(1970, 1, 1, 0, 0, 0, 0);
            long currentMillis = (currentTicks - dtFrom.Ticks) / 10000 / 1000;
            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() > 0)
                        {
                            //如果添加成功,获取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 = 1;//定义当前页码
            $scope.pageSize = 5;//定义每页包含的数目;一般通过后台配置或者webconfig
            //定义一个函数,用于将后台的json字符串数据转化为json数组
            //1:后台直接传{开头有问题;2:split先这样吧,把流程跑通
            $scope.behindChangeJsonArray = function (strResult) {
                strResult = strResult.replace("result:\\{", "");
                var strArray = strResult.split("@#$%");
                var jsonArray = [];
                for (var i = 0; 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(1);
            //将函数放到$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[0].error == 0) {
                        //alert('成功了'); 刷新页面,通过unshift把最新的是数据放置在最上面
                        $scope.replies.unshift({
                            id: result[0].ID,
                            content: $scope.inputText,
                            time: result[0].time,
                            acc: 0,
                            ref: 0
                        });
                        //确保每页最多显示6条
                        if ($scope.replies.length>5) {
                            $scope.replies.pop();
                        }
                        //清空输入框内容
                        $scope.inputText = "";
                    } else {
                        alert('添加失败');
                    }
                }).error(function () {
                    alert('错误');
                });
            }
            //页码--开始
            function setCurrentPage(pages) {
                $scope.pages = [];//先清空一下
                for (var i = 1; 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*1000|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 = 1;//定义当前页码
            $scope.pageSize = 5;//定义每页包含的数目;一般通过后台配置或者webconfig
            //定义一个函数,用于将后台的json字符串数据转化为json数组
            //1:后台直接传{开头有问题;2:split先这样吧,把流程跑通
            $scope.behindChangeJsonArray = function (strResult) {
                strResult = strResult.replace("result:\\{", "");
                var strArray = strResult.split("@#$%");
                var jsonArray = [];
                for (var i = 0; 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(1);
            //将函数放到$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[0].error == 0) {
                        //alert('成功了'); 刷新页面,通过unshift把最新的是数据放置在最上面
                        $scope.replies.unshift({
                            id: result[0].ID,
                            content: $scope.inputText,
                            time: result[0].time,
                            acc: 0,
                            ref: 0
                        });
                        //确保每页最多显示6条
                        if ($scope.replies.length>5) {
                            $scope.replies.pop();
                        }
                        //清空输入框内容
                        $scope.inputText = "";
                    } else {
                        alert('添加失败');
                    }
                }).error(function () {
                    alert('错误');
                });
            }
            //页码--开始
            function setCurrentPage(pages) {
                $scope.pages = [];//先清空一下
                for (var i = 1; 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 = 0; 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*1000|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 = 1;//定义当前页码
            $scope.pageSize = 5;//定义每页包含的数目;一般通过后台配置或者webconfig
            //定义一个函数,用于将后台的json字符串数据转化为json数组
            //1:后台直接传{开头有问题;2:split先这样吧,把流程跑通
            $scope.behindChangeJsonArray = function (strResult) {
                strResult = strResult.replace("result:\\{", "");
                var strArray = strResult.split("@#$%");
                var jsonArray = [];
                for (var i = 0; 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(1);
            //将函数放到$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[0].error == 0) {
                        //alert('成功了'); 刷新页面,通过unshift把最新的是数据放置在最上面
                        $scope.replies.unshift({
                            id: result[0].ID,
                            content: $scope.inputText,
                            time: result[0].time,
                            acc: 0,
                            ref: 0
                        });
                        //确保每页最多显示6条
                        if ($scope.replies.length>5) {
                            $scope.replies.pop();
                        }
                        //清空输入框内容
                        $scope.inputText = "";
                    } else {
                        alert('添加失败');
                    }
                }).error(function () {
                    alert('错误');
                });
            }
            //页码--开始
            function setCurrentPage(pages) {
                $scope.pages = [];//先清空一下
                for (var i = 1; 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 = 0; 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*1000|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");

 

posted @ 2018-05-30 11:24  逍遥小天狼  阅读(218)  评论(0编辑  收藏  举报