angularJs分页对象实现

首先需要使用指令(directives),然后共享socpe对象即可,html里输入:

<div class="pages">
    <page-html page="{{pageData.page}}" pageTotal="{{pageData.pageTotle}}" method="read"></page-html>
</div>

directives文件中创建pageHtml指令:

.directive("pageHtml",function () {
    return{
        restrict:'EA',
        replace:true,
        link:function (scope,ele,attr,ctrl) {
            scope.initPage = function(){
                scope.pages = [];
                if(typeof scope.pageData == "object" && scope.pageData.pageTotle > 1){
                    var i = scope.pageData.page;
                    i -= 2;
                    if(i < 1){
                        i = 1
                    }
                    for(;i <= scope.pageData.pageTotle; i++){
                        scope.pages.push(i)
                        if(scope.pages.length >= 5){
                            break;
                        }
                    }
                }
            }
            scope.initPage()
        },
        controller: function ($scope, $element, $attrs) {

            var _method = $attrs.method
            $scope.selectPage = function(page){
                if(page == "pre"){
                    if($scope.pageData.page > 1){
                        $scope.pageData.page--;
                        page = $scope.pageData.page;
                    }
                }else if(page == "next"){
                    if($scope.pageData.page < $scope.pageData.pageTotle){
                        $scope.pageData.page++;
                        page = $scope.pageData.page;
                    }
                }else{
                    $scope.pageData.page = page;
                }
                if($scope.pageData.page > 0 && $scope.pageData.page <= $scope.pageData.pageTotle){
                    $scope.initPage()
                    if(typeof _method  == "string"){
                        $scope[_method](page);
                    }else{
                        $scope.read(page);
                    }
                }
            }
        },
        template: '<nav ng-if="pageData.pageTotle > 1"><ul class="pagination">' +
        '<li><a class="disabled cursor-pointer" ng-click="selectPage(\'pre\')"><span aria-hidden="true">上一页</span></a></li>' +
        '<li ng-repeat="(i,n) in pages track by i" ng-click="selectPage(n)" class="cursor-pointer {{n == pageData.page ? \'active\': \'\'}}"><a>{{n}}</a></li>'+
        '<li><a class="Previous cursor-pointer" ng-click="selectPage(\'next\')"><span aria-hidden="true">下一页</span></a></li>' +
        '</ul></nav>'
    }
})

一个简单的分页效果就出来了。

 

angularJS使用directive指令、filter来做表单过滤器

directive做过滤器要人性化很多,但是如果是简单的过滤也可以使用filter来做,设置一个全局变量保存数据验证结果,等到提交表单的时候验证全局变量就可以了:

.directive("myFilter",function(){
    var css = {
        _valid:function(ele){
            ele.removeClass("ng-invalid");
            ele.next().removeClass("hide");
            ele.next().removeClass("input_remove");
            ele.next().removeClass("glyphicon-remove");

            ele.addClass("ng-valid");
            ele.next().addClass("input_ok");
            ele.next().addClass("glyphicon-ok");
        },
        _invalid:function(ele){
            ele.removeClass("ng-valid");
            ele.next().removeClass("input_ok");
            ele.next().removeClass("glyphicon-ok");

            ele.addClass("ng-invalid");
            ele.next().addClass("input_remove");
            ele.next().addClass("glyphicon-remove");
        }
    };
    return {
        require:'ngModel',
        link:function(scope,ele,arrts){
            scope.$watch(arrts.ngModel,function(newVal,oldVal){
                if(typeof newVal != "undefined"){
                    css._valid(ele);
                    if(typeof arrts.type != "undefined"){
                        switch (arrts.type){
                            case 'text':
                                if(typeof newVal != "string"){
                                    css._invalid(ele);
                                }

                                if(typeof arrts.min != "undefined"){
                                    if(newVal.length < arrts.min){
                                        css._invalid(ele);
                                    }
                                }

                                if(typeof arrts.max != "undefined"){
                                    if(newVal.length > arrts.max){
                                        css._invalid(ele);
                                    }
                                }
                                break;
                            case 'number2':
                                var filter  = /^[0-9]+.?[0-9]*$/;
                                if(!filter.test(newVal)){
                                    css._invalid(ele);
                                }

                                if(typeof arrts.min != "undefined"){
                                    if(newVal < parseInt(arrts.min)){

                                        css._invalid(ele);
                                    }
                                }

                                if(typeof arrts.max != "undefined"){
                                    if(newVal > parseInt(arrts.max)){
                                        css._invalid(ele);
                                    }
                                }
                                break;
                            case 'email2':
                                var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                                if(!filter.test(newVal)){
                                    css._invalid(ele);
                                }
                                break;
                        }
                    }
                }


            });
        }

    };
})
.filter('email2',function(){
    //感觉这个不人性化,也可能是我不会用吧
    return function(input,length){
        if(typeof input == "undefined" || length < input.length){
            //c("输入不合规");
        }
        return input;
    }
})

 

下面是style的代码:

input.ng-invalid {
    border: 1px solid red;
}
input.ng-valid {
    border: 1px solid green;
}
.input_ok{
    position: absolute;
    z-index: 100;
    right: 1%;
    top: 8px;
    color: #299429;
}
.input_remove{
    position: absolute;
    z-index: 100;
    right: 1%;
    top: 8px;
    color: #ff0000;
}
.form-contant p{
    position: relative;
}

下面是表单html的代码:

<div class="form-contant">
    <h1>Register</h1>
    <p>
        <input type="text" ng-model="user_name" placeholder="请输入用户名" class="form-control" my-filter data="{{user_name|email2:4}}" min="4" max="20">
        <i class="glyphicon glyphicon-ok hide"></i>
    </p>
    <p>
        <input type="text" ng-model="user_pwd" placeholder="请输入密码" class="form-control" my-filter min="4" max="20">
        <i class="glyphicon glyphicon-ok hide"></i>
    </p>
    <p>
        <input type="number2" ng-model="age" placeholder="请输入年龄" class="form-control" my-filter min="4" max="102">
        <i class="glyphicon glyphicon-ok hide"></i>
    </p>
    <p>
        <input type="email2" ng-model="email" placeholder="请输入邮箱" class="form-control" value="" my-filter  min="6" max="50">
        <i class="glyphicon glyphicon-ok hide"></i>
    </p>


    <br>
    <button type="button" class="form-control" ng-click="get()">get</button>
    <button type="button" class="form-control" ng-click="save()">save</button>
    <button type="button" class="form-control" ng-click="put()">put</button>
</div>

 

 

AngularJS中$http、$httpProvider、$resource操作笔记

1.设置httpProvider头

var app = angular.module(“Myapp”, [‘ngRoute’])
.config([‘$locationProvider’,’apikey’,function($locationProvider,apikey){
$locationProvider.html5Mode(false);
$locationProvider.hashPrefix(“!”)
}])
.config(function ($routeProvider,$httpProvider) {
//设置http头
$httpProvider.defaults.headers.common[“X-Response-Code-By”] = “Angular1.3.8″;

angularJS学习笔记

QQ截图20160929161813

<script>
    function c(str) {
        console.log(str)
    }

    var app = angular.module("Myapp", ['ngRoute'])
            .config(['$locationProvider',function($locationProvider){
                $locationProvider.html5Mode(false);
                $locationProvider.hashPrefix("!")
            }])
            .config(function ($routeProvider) {

                $routeProvider
                        .when('/', {
                            templateUrl: 'views/main.html',
                            controller: 'MainCtrl'
                        })
                        .when('/about', {
                            templateUrl: 'views/about.html',
                            controller: 'AboutCtrl',

                        })
                        .when('/action', {
                            templateUrl: 'views/action.html',
                            controller: 'ActionCtrl'
                        })
                        .when('/contact:q', {
                            templateUrl: 'views/contact.html',
                            controller: 'ContactCtrl'
                        }).when("/register", {
                            templateUrl: 'views/register.html',
                            controller: 'registerCtrl'
                        })
                        .otherwise({
                            redirectTo: '/'
                        })
            })
            .run(['$rootScope','$location',function ($rootScope,$location) {
                $rootScope.title = "网站的标题";
                $rootScope.keywords = "网站的关键词";
                $rootScope.description = "网站的描述";

                //路由开始
                $rootScope.$on('$routeChangeStart',function(evt, next, current){

                });

                //路由成功
                $rootScope.$on('$routeChangeSuccess', function(evt, next, previous) {

                });

                //路由错误
                $rootScope.$on('$routeChangeError', function(current, previous, rejection) {
                    c('$routeChangeError')
                    c(current)
                    c(previous)
                    c(rejection)
                });

            }])
            .factory('myFactory', function(){
                var service = {1:"a",2:"b",3:"c"};
                return service;
            })
            .directive('myDirective', function(){
                return {
                    template: '<button>Click me</button>'
                }
            })
            .directive('ensureUnique', function ($http) {
                return {
                    require: 'ngModel',
                    link: function (scope, ele, attrs, cfg) {
                        scope.$watch(attrs.ngModel, function () {
                            $http({
                                method: 'POST',
                                url: '/1.php',
                                params: {filed: attrs.name, value: attrs.ngModel, value2: ele[0].value}

                            }).success(function (data, status, headers, fg) {
                                c(data);

                            }).error(function (data, status, headers, fg) {
                                alert('网络繁忙!');
                            })
                        });
                    }
                };
            })

            .controller('MainCtrl', function ($scope, $routeParams) {
                $scope.context = "Main页面标题";
                $scope.add = function (num) {
                    ++num;
                    alert("num:" + num);
                };
                $scope.name = {name: "a001", pwd: "a123456"};

            })
            .controller('AboutCtrl', function ($scope, $routeParams, $filter) {
                $scope.context = "关于我们";
                $scope.other = "谢谢支持!";

//

                //$scope.name = $filter('lowercase');
                $scope.unClock = function () {
                    $scope.isDisabled = true;
                    // alert('ok');
                }
                $scope.myChange = function (d) {
                    c(d);
                }
                $scope.submitForm = function (d) {
                    c(d);
                }

                $scope.people = [
                    {name: "小A", city: "重庆"},
                    {name: "小b", city: "成都"},
                    {name: "小c", city: "武汉"},
                    {name: "小d", city: "广州"},
                    {name: "小e", city: "上海"}
                ];

                $scope.fields = [
                    {isRequired: true, name: "user_name", placeholder: "请输入用户名", model1: "", msg: "请输入用户名"},
                    {isRequired: true, name: "user_pwd", placeholder: "请输入用户密码", model1: "", msg: "请输入用户密码"},
                    {isRequired: true, name: "email", placeholder: "请输入用户邮箱", model1: "", msg: "请输入用户邮箱"},
                ]
                $scope.cx = "testcx"


            }).controller('ActionCtrl', function ($scope, $routeParams) {
                $scope.context = "Action测试页面";


            }).controller('ContactCtrl', function ($scope, $routeParams) {
                $scope.context = "联系人";


            }).controller("nowDae", function ($scope) {

                $scope.now = new Date();
                $scope.do = function () {

                    $.ajax({
                        url: '/1.php',
                        type: 'post',
                        dataType: 'json',
                        async: false,
                        data: {id: 10, user_name: 'a001', user_pwd: '123456'},
                        success: function (data) {
                            c("data>>>>>");
                            c(data);
                        }
                    })
                }

            }).controller("registerCtrl", function ($scope, $routeParams) {
                $scope.context = "用户注册";
                $scope.showAgreement = function () {
                    alert("用户协议...");
                };

                $scope.doreg = function () {

                    alert('sdaf');
                    return false;
                }


            })
            .filter('number2', function () {
                return function (input) {

                    return "过滤过的:" + input;


                };
            }).filter('email2', function () {
                return function (input) {
                    if (input) {
                        return "filter:" + input;
                    }

                };
            })



</script>

代码包下载:百度网盘

http://pan.baidu.com/s/1kUH1H0F

AngularJS多重视图和路由教程

多重视图和路由

能够从页面的一个视图跳转到另外一个视图,对单页面应用来讲是至关重要的。当应用变得越来越复杂时,我们需要一个合理的方式来管理用户在使用过程中看到的界面。也许我们已经通过在主HTML中添加行内的模板代码,实现了对视图的管理,但这些代码也会变得越来越复杂和难以管理,同时其他开发者也很难加入到开发工作中来。另外,由于应用的状态信息会包含在URL中,我们也无法将代码直接复制并发送给朋友。除了用 ng-include 指令在视图中引用多个模板外,更好的做法是将视图分解成布局和模板视图,并且根据用户当前访问的URL来展示对应的视图。我们会将这些模板分解到视图中,并在布局模板内进行组装。AngularJS允许我们在 $route服务的提供者 $routeProvider 中通过声明路由来实现这个功能。通过 $routeProvider ,可以发挥出浏览器历史导航的优势,并让用户基于浏览器当前的URL地址创建书签或分享页面。

安装

从1.2版本开始,AngularJS将 ngRoutes 从核心代码中剥离出来成为独立的模块。我们需要安装并引用它,才能够在AngularJS应用中正常地使用路由功能。

可以从code.angularjs.org下载它,然后保存到一个可以在HTML页面中进行引用的位置,例如js/vendor/angular-route.js。也可以用Bower来安装,这样会将它存放到Bower的目录中。

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |