2014-12-11 51 views
0

我正在尝试设置管理页面。有许多元素,当你点击其中一个元素时,下拉菜单会显示更多信息,特别是高图表图。目前我正在使用一个指令来创建图表div,但我一直无法找到控制指令何时呈现的方式,它会在页面加载时自动发生。Angular Directives:如何控制何时显示图表

不幸的是,我有超过200个这样的元素,并且在页面当前设置的情况下,每次页面加载时都会呈现所有200个图表。显然,这会导致糟糕的用户体验。

我对webdev总体上有点新。我不确定我是否以正确的方式处理这个问题。以下是相关代码:

<div class="source" ng-repeat="source in sources"> 
    ... 
    <div source-dropdown-graph class="sources-dropdown-graph" ng-show="showDropdownGraph == source.myIndex" source="source"></div> 
</div> 

我正在使用ng-show在用户单击时切换图形的可见性。从指令:

return { 
    scope: { 
     source: "=source" 
    }, 
    templateUrl: 'source-dropdown-graph.html', 
    link: link 
}; 

链接功能只是呈现图形。最后是模板的html:

<div id="chart-container" style="min-width: 70%; max-width: 1200px; height: 300px; margin: 0 auto"></div> 

就像我说的,这是所有的工作,除了渲染一切权利的蝙蝠。我想在是否渲染图表的source对象中设置一个标志,但我不知道如何在该值发生变化时重新渲染它。在这种情况下,指令是否正确?就像我说的,我对web开发人员还比较陌生,所以我愿意完全不同。谢谢!

+1

最简单的改变是将'ng-show'换成'ng-if'。 – 2014-12-11 00:39:33

回答

1

除了使用ng-if而不是ng-show来限制DOM中元素的数量外,您还可以在指令中使用手表来监视source的变化并控制何时或不需要渲染。

return { 
    scope: { 
     source: "=" 
    }, 
    templateUrl: 'source-dropdown-graph.html', 
    link: link 
}; 

function link (scope, element, attrs) { 
    scope.$watch('source', function (newValue, oldValue) { 
     // condition(s) where you don't want to render 
     // i.e. if the source is undefined or null 
     if (!newValue || (newValue === oldValue)) { 
      return; 
     } 

     // otherwise, render it every time source changes 
     render(); 
    }); 

    function render() { 
     // your rendering logic 
    } 
} 
相关问题