D3学习笔记一 bars in angular

1 使用factory在页面添加d3.js。也可以选择在页面直接引入d3.js。

d3.factory(‘d3Service‘,[‘$document‘,‘$q‘, ‘$rootScope‘, function($document, $q, $rootScope){
    var d = $q.defer();
    function onScriptLoad(){
        $rootScope.$apply(function(){d.resolve(window.d3);})
    }

  // 建立一个D3的脚本标签,当这个标签加载完毕后运行onScriptLoad方法来load D3

     var scriptTag = $document[0].createElement(‘script‘);

    scriptTag.type=‘text/javascript‘;
    scriptTag.async=true;
    scriptTag.src=‘../js/common/d3/d3.js‘;
    scriptTag.onreadystatechange = function(){
        if(this.readyState == ‘complete‘)onScriptLoad();
    };
    scriptTag.onload = onScriptLoad;

    var s = $document[0].getElementsByTagName(‘body‘)[0];

    s.appendChild(scriptTag);

    return {
        d3:function(){return d.promise}
    };
}]);

2 建立一个d3 directive。

d3Module.directive(‘d3Bars‘,[‘$window‘, ‘d3Service‘,function($window, d3Service){
    return{
        restrict:‘EA‘,
        scope:{
            data:‘=‘,
            clickBar:‘&‘
        },
        link:function(scope, element, attrs){
            d3Service.d3().then(function(d3){
                var svg = d3.select(element[0]).append(‘svg‘).style(‘width‘,‘100%‘);

                var margin = parseInt(attrs.margin) || 20,
                    barHeight = parseInt(attrs.barHeight) || 20,
                    barPadding = parseInt(attrs.barPadding) || 5;
                //页面大小调整时元素也进行调整
                window.onresize = function(){
                    scope.$apply();
                };

                //scope.data = [
                //    {name: ‘Greg‘, score:98},
                //    {name: ‘Ari‘, score:96},
                //    {name: ‘Q‘, score:75},
                //    {name: ‘Loser‘, score:48}
                //];

                scope.$watch(function(){
                    return angular.element($window)[0].innerWidth;
                },function(){
                    scope.render(scope.data)
                });

                scope.render = function(data) {
                    //刷新前移除之前的svg
                    svg.selectAll(‘*‘).remove();

                    if(!data) return;

                    // 设置变量
                    var width = d3.select(element[0]).node().offsetWidth - margin,
                    // 计算高度
                        height = scope.data.length * (barHeight + barPadding),
                    // 使用category20()函数来生成颜色
                        color = d3.scale.category20(),
                    // 定义比例尺
                        xScale = d3.scale.linear()
                            .domain([0, d3.max(data, function (d) {
                                return d.score;
                            })])
                            .range([0, width]);

                    svg.attr(‘height‘, height);

                    //生成柱状图的长方形
                    svg.selectAll(‘rect‘)
                        .data(data).enter()
                        .append(‘rect‘)
                        .attr(‘height‘,barHeight)
                        .attr(‘width‘,140)
                        .attr(‘x‘,Math.round(margin/2))
                        .attr(‘y‘,function(d,i){
                            return i * (barHeight + barPadding);
                        })
                        .attr(‘fill‘,function(d){return color(d.score);})
                        .transition()
                        .duration(1000)              //根据比例尺计算柱状图的宽度
                        .attr(‘width‘,function(d){
                            return xScale(d.score);
                        });
                    svg.selectAll(‘rect‘).on(‘click‘,function(d,i){
                            return scope.clickBar({item: d});
                        })

                }
            });

        }
    }
}]); 

效果图:

时间: 2024-08-01 20:07:23

D3学习笔记一 bars in angular的相关文章

[学习笔记] 七步从Angular.JS菜鸟到专家(3):数据绑定和AJAX [转]

这是"AngularJS - 七步从菜鸟到专家"系列的第三篇. 在第一篇,我们展示了如何开始搭建一个AngularaJS应用.第二篇我们讨论了scope和 $scope 的功能. 通过这整个系列的教程,我们会开发一个NPR(美国全国公共广播电台)广播的音频播放器,它能显示Morning Edition节目里现在播出的最新故事,并在我们的浏览器里播放.完成版的Demo可以看这里. 第三部分 数据绑定 通过把一个文本输入框绑定到person.name属性上,就能把我们的应用变得更有趣一点.这一步建立

angular 学习笔记

每天进步一点点,学习笔记 笔记来自  angular权威指南 如果想要屏蔽浏览器对表单的默认验证行为,可以在表单元素上添加 novalidate 标记. 而按钮标签则完全忽略 hr e f 属性,并不会在被点击时有同样的行为. 指令本质上就是AngularJS扩展具有自定义功能的HTML元素的途径.例如,我们可以创建一个自定义元素,它实现了 <video> 标签的功能并且能在所有浏览器中工作: directive() 方法返回的对象中包含了用来定义和配置指令所需的方法和属性. 声明指令本质上是

[Pro Angular.JS]学习笔记1.1:设置开发环境

可以使用yeoman.io,很方便.我已经写了一篇随笔,介绍如何使用.这里也有一篇介绍的文章:http://www.cnblogs.com/JoannaQ/p/3756281.html 代码编辑器,在Mac下用了一下WebStorm,太恶心了.另外发现书的作者使用的开发环境是Windows + VS Express 2013,为了方便学习,我也使用VS Express 2013 Update2.VS2013用起来蛮舒服的,把WebStorm比得跟驼屎一样.也许是因为我没用习惯吧. 1.安装Nod

angular学习笔记(八)

本篇介绍angular控制视图的显示和隐藏: 通过给元素添加ng-show属性或者ng-hide属性来控制视图的显示或隐藏: ng-show: 绑定的数据值为true时,显示元素,值为false时,隐藏元素 ng-hide: 绑定的数据值为true时,隐藏元素,值为false时,显示元素 (其实只要用到其中一个就可以了) 下面来看个简单的例子,点击按钮可以显示/隐藏元素: <!DOCTYPE html> <html ng-app> <head> <title>

angular学习笔记(二十八)-$http(6)-使用ngResource模块构建RESTful架构

ngResource模块是angular专门为RESTful架构而设计的一个模块,它提供了'$resource'模块,$resource模块是基于$http的一个封装.下面来看看它的详细用法 1.引入angular-resource.min.js文件 2.在模块中依赖ngResourece,在服务中注入$resource var HttpREST = angular.module('HttpREST',['ngResource']); HttpREST.factory('cardResource

Angular JS 学习笔记

特定领域语言 编译器:遍历DOM来查找和它相关的属性, 分为编译和链接两个阶段, 指令:当关联的HTML结构进入编译阶段时应该执行的操作,可以写在名称里,属性里,css类名里:本质上是函数 稳定的DOM:绑定了数据模型的DOM元素的实例不会在绑定的生命周期发生改变 作用域:用来检测模型的改变和为表达式提供执行上下文的 AngularJS 和其它模板系统不同,它使用的是DOM而不是字符串 指令: 由某个属性.元素名称.css类名出现而导致的行为,或者说是DOM的变化 Filter过滤器:扮演着数据

angular学习笔记(五)-阶乘计算实例(1)

<!DOCTYPE html> <html ng-app> <head> <title>2.3.2计算阶乘实例1</title> <meta charset="utf-8"> <script src="../angular.js"></script> <script src="script.js"></script> </

angular学习笔记(二十三)-$http(1)-api

之前说到的$http.get和$http.post,都是基于$http的快捷方式.下面来说说完整的$http: $http(config) $http接受一个json格式的参数config: config的格式如下: { method:字符串 , url:字符串, params:json对象, data:请求数据, headers:请求头, transformRequest:函数,转换post请求的数据的格式, transformResponse:函数,转换响应到的数据的格式, cache:布尔

angular学习笔记(二十七)-$http(5)-使用$http构建RESTful架构

在angular中有一个特别为RESTful架构而定制的服务,是在$http的基础上进行了封装. 但是为了学习,我们先看看用直接$http是如何构建RESTful架构的: 假设有一个银行卡的列表.需要的功能有: 可以通过id来获取用户123的指定id的卡     'GET'  'card/user/123/id' 可以获取用户123的所有的银行卡             'GET'  'card/user/123' 可以更新用户123的指定id的卡                'POST' '