2015-06-24 67 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>