AngularJS

作者: 持而盈 | 来源:发表于2017-02-16 15:11 被阅读66次

    过滤器

    自定义过滤器:

    filter的定义和js中的使用.

    var app = angular.module('app', ['app.filters']);
    
    app.controller('mController', ['$scope', '$filter',
        function ($scope, $filter) {
            var ary = ["lily", "lucy", "mike"];
            //用filter替换数组中的元素,如果filter有多个参数就写多个,
            var newAry = $filter("replace")(ary, "mike", "tom");
            console.log("新数组是:" + newAry);
    
        }]);
    
    var mFilters = angular.module('app.filters', []);
    
    
    /**
     * 定义filter,替换数组中的一个元素.filter最好都写在一个单独的module中,这样方便引用.
     * 可以定义多个参数,第一个参数默认是 | 左边的源.
     */
    mFilters.filter("replace", function () {
        return function (ary, replaceItem, withItem) {
            angular.forEach(ary, function (item, index) {
                if (item === replaceItem) {
                    ary.splice(index, 1, withItem);
                }
            });
            return ary;
        }
    });
    

    在html中使用, filter可以连续使用多个.
    <div>{{["a","b","c","d"]| replace:"b":"q"}}</div>

    $watch

    js:
    //监听某一变量的变化,并执行函数.
    $scope.$watch("user.name", function (now, old) {
        console.log(now + "-->" + old);
        if (now && now.length > 0) {
            if (now.length > 6) {
                $scope.message = "";
            } else {
                $scope.message = "输入的用户名不合法!";
            }
        } else {
            $scope.message = "请输入用户名!";
        }
    })
    
    html:
    <input type="text" ng-model="user.name">
    <div>{{message}}</div>
    

    指令

    定义语法:

    app.directive('breadcrumb', function () {
        return {
            //局部作用域,如果写了link函数,可以不写这个.
            scope: {
                //@表示值与名字一致
                data: '@'
            },
            template: "",
            templateUrl: "templates/breadcrumb.html",
            replace: true,
            //推荐使用这个
            link: function (scope, element, attributes) {
                scope.data = JSON.parse(attributes.data);
            }
        }
    });
    

    示例 js:

    var app = angular.module('app', []);
    app.controller('mController', ['$scope', '$filter',
        function ($scope, $filter) {
            $scope.pathData = ['home', 'it', 'java'];
        }]);
    
    
    app.directive('breadcrumb', function () {
        return {
            scope: {
                data: '@'
            },
            template: "",
            templateUrl: "templates/breadcrumb.html",
            replace: true,
            link: function (scope, element, attributes) {
                scope.data = JSON.parse(attributes.data);
            }
        }
    });
    

    html:

    <breadcrumb data="{{pathData}}"></breadcrumb>
    

    模板html:

    <ol class="breadcrumb">
        <li ng-repeat="path in data track by $index" ng-class="{active:$last}">
            <a href="#" ng-if="!$last">{{path}}</a>
            <span ng-if="$last">{{path}}</span>
        </li>
    </ol>
    

    Ui-router 路由

    安装:

    Npm install angular-ui-router –save

    编写路由配置文件 Config.js

    var app = angular.module('app', ['ui.router']);
    
    app.config(function ($stateProvider) {
        $stateProvider
            .state('going', {
                templateUrl: "going_on.html",
                controller: 'goingController'
            })
            .state('hot', {
                //html的路径,相对路径是相对于主页面.
                templateUrl: "in_hot.html",
                //注意 这里写了Controller html中就不能在写了,否则Controller会被执行2次
                controller: 'hotController',
                //传递参数: 参数名+null 就行.
                params: {name: null, age: null}
    
            })
            .state('top', {
                templateUrl: "top_250.html",
                controller: 'topController'
            });
    });
    

    编写页面

    Ui-view 指定 页面容器

    .container-fluid
       .row
          .col-sm-3.col-md-2.sidebar
             ul.nav.nav-sidebar
                li(ng-class="{active:location.location=='hot'}")
                   a(ui-sref='hot({name:name,age:age})') 正在热映
                      span.sr-only (current)
                li(ng-class="{active:location.location=='going'}")
                   a(ui-sref='going') 即将上映
                li(ng-class="{active:location.location=='top'}")
                   a(ui-sref='top') Top250
          .col-sm-9.col-sm-offset-3.col-md-10.col-md-offset-2.main(ui-view)
             h1 欢迎使用
    

    执行跳转动作

    1. 方式一: 写在html中
    a(ui-sref='hot({name:name,age:age})') 正在热映 
    
    1. 方式二: 在js 中触发
    app.controller('mController', function ($scope, $state, $stateParams) {
        $scope.name = 'xiao ming';
        $scope.age = 55;
        $state.go('hot', {name: $scope.name, age: $scope.age});
    });
    

    接受跳转参数

    app.controller('hotController', function ($scope, $rootScope, $stateParams) {
        console.log("得到参数" + $stateParams.name);
        console.log("得到参数" + $stateParams.age);
    });
    

    Ui-bootstrap

    • 安装依赖:
    "angular": "^1.5.8",
    "angular-animate": "^1.5.8",
    "angular-ui-bootstrap": "^2.0.1",
    "bootstrap": "^3.3.7"
    
    • 引入:
    //ui-bootstrap
    link(href='../node_modules/angular-ui-bootstrap/dist/ui-bootstrap-csp.css', rel='stylesheet')
    script(src='../node_modules/angular-ui-bootstrap/dist/ui-bootstrap-tpls.js')
    script(src='../node_modules/angular-animate/angular-animate.min.js')
    

    Ng-table

    安装:

    npm install ng-table –save

    //ng-table
    link(href='../node_modules/ng-table/dist/ng-table.css', rel='stylesheet')
    script(src='../node_modules/ng-table/dist/ng-table.min.js')
    

    Dataset 静态数据

    Controller

    app.controller('topController', function ($scope, $filter, $http, NgTableParams, $rootScope, tableSvc) {
        $rootScope.location = 'top';
        $scope.users = [];
        $scope.tableParams = new NgTableParams({}, {
            dataset: $scope.user
        });
    
        tableSvc.getUsers().then(function (data) {
            $scope.users = data;
            //执行异步任务得到数据后,要重新设置tableParams,相当于刷新table.
            $scope.tableParams.settings({dataset: $scope.users});
        }, function (data) {
            console.log("获取用户错误:" + data);
        });
    });
    

    jade

    table.table(ng-table="tableParams")
       tr(ng-repeat='user in $data')
          td(data-title="'Name'", filter="{name: 'text'}", sortable="'name'") {{user.name}}
          td(data-title="'Age'", filter="{age: 'number'}", sortable="'age'") {{user.age}}
    

    getData 动态数据

    getData方法要求返回一个promise对象. 使用这个方法, 对表格的排序, 过滤. 都是动态的, ng-table 会根据用户点击 生成url参数数组, 然后由用户根据url重新请求服务器, 并由服务器来做:排序,过滤操作. 然后展示数据. 这需要服务器API的支持.

    Html代码不变, Controller:

    $scope.tableParams = new NgTableParams({
        count: 5
    }, {
        getData: function (params) {
            console.log("请求参数");
            console.log(params.url());
            params.total(200);
            //params.url() 是ng-table根据用户操作生成的路径参数.
            return tableSvc.getUsers(params.url());
        }
    });
    

    相关文章

      网友评论

          本文标题:AngularJS

          本文链接:https://www.haomeiwen.com/subject/djhhwttx.html