2015-06-24 72 views
0

请考虑以下代码块。销毁和重建指令

控制器

function($scope){ 
    var currentIndex = 1, 
    shapes = [{type:'square',/*...*/},{type:'triangle',/*...*/},{type:'triangle',/*...*/},], 

    $scope.goToNextShape = function(){ 
     currentIndex++ 
     $scope.currentShape = shapes[currentIndex] 
    } 

} 

HTML

<square data="currentShape" ng-if="currentShape.type = 'square'" /> 
<circle data="currentShape" ng-if="currentShape.type = 'circle'" /> 
<triangle data="currentShape" ng-if="currentShape.type = 'triangle'" /> 
<rectangle data="currentShape" ng-if="currentShape.type = 'rectangle'" /> 
<trapezoid data="currentShape" ng-if="currentShape.type = 'trapezoid'" /> 
<button ng-click="goToNextShape()></button> 

予一次显示一个形状,并且每种形状经由其自己的指令渲染。该指令使用具有动画和其他功能的其他组件。目前,如果我在一个方形对象之后有一个圆圈,所有的都很棒,因为由于ng-if和一个圆圈的构建,指令被破坏了。但是,如果我有两个正方形背靠背,那么指令不会被重建,因为ng-if保持不变。我如何做角度销毁和重建指令时,我goToNextShape()

+1

这不是有效的HTML。这不足以说明您的问题。 – zeroflagL

+0

这个问题的html就足够了。这段代码有点混乱,我会重写。 – Meeker

+0

现在我明白了这个问题。然而,我不明白的是为什么你想要重建指令。换句话说:会有什么不同? – zeroflagL

回答

0

我做了什么,实际上做了一个很好的ux经验。我在形状之间有一个形状加载屏幕。当该屏幕开启时,我通过将其放入具有ng-if的父元素来销毁当前的形状。

HTML

<!-- when shapeIsLoaded = false all directives will be destroyed ---> 
<!-- just need to make sure a digest cycle is run between shapeIsLoaded switching between true/false --->  
<div ng-if="shapeIsLoaded"> 
    <square data="currentShape" ng-if="currentShape.type = 'square'" /> 
    <circle data="currentShape" ng-if="currentShape.type = 'circle'" /> 
    <triangle data="currentShape" ng-if="currentShape.type = 'triangle'" /> 
    <rectangle data="currentShape" ng-if="currentShape.type = 'rectangle'" /> 
    <trapezoid data="currentShape" ng-if="currentShape.type = 'trapezoid'" /> 
    <button ng-click="goToNextShape()></button> 
</div>