【问题标题】:Set a width of a div as a percentage of parent in angular.js在angular.js中将div的宽度设置为父级的百分比
【发布时间】:2014-09-05 13:45:37
【问题描述】:

我在 Jquery 中有一个条形图,我想以角度重新创建它。该图只是样式化的 div,其宽度设置为父级的百分比,如下所示

$('.item-skills').each(function(){
  newWidth = $(this).parent().width() * $(this).data('percent');
  $(this).width(newWidth);
});

我想把它放在一个名为 bar-graph 的指令中,以便像这样使用

<div bar-graph="0.85"></div>

这会产生一个宽度是父母的 85% 的 div

编辑:我在这里找到了解决方案Angularjs adjust width based on parent element width

【问题讨论】:

  • bar-graph 不是有效属性

标签: javascript html css angularjs


【解决方案1】:

你所追求的是一个指令。 like this question on stackoverflow 这是来自 AngularJS 的creating directives 的链接

【讨论】:

    【解决方案2】:

    如果其他人需要帮助,下面是我的解决方案

        (function(angular) {
    
          var
            definitions;
    
          definitions = [
            niBargraph
          ];
    
          angular.module('ni.Bargraph').directive('niBargraph', definitions);
    
          function niBargraph() {
    
            return {
              scope: {
                percent: '@niBargraph'
              },
              link: setSize
            };
    
            function setSize(scope, elm, attrs, ctrl) {
                elm.css({
                    width: elm.parent()[0].offsetWidth * parseFloat(scope.percent)
                });
            }
          }
        })(angular);
    

    【讨论】:

      猜你喜欢
      • 2022-11-07
      • 2013-03-13
      • 2019-06-28
      • 1970-01-01
      • 2012-02-05
      • 2011-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多