2015-10-20 68 views
0

我使用這個代碼來觀看兒童身高的變化:ng-show | NG-隱藏:看元素高度

$scope.$watch(function() { 
    return element.children().height(); 
}, 
function (newHeight) { 
    if (newHeight) { 
     element.height(newHeight); 
    } 
}); 

它工作得很好用ng-if,但ng-show | ng-hide不火的高度變化的事件。 當我使用ng-show | ng-hide指令時,有什麼方法可以觀察高度嗎?


實施例:

<div class="form-slider"> 
    <div ng-if="step === 1" class="animate"> 
    <div ng-show="error">Error message</div> 
    Some content 
    </div> 
    <div ng-if="step === 2" class="animate"> 
    <div ng-show="error">Error message</div> 
    Some content 
    </div> 
</div> 

我使用動畫來ng-if秒之間切換,所以: .form-slider具有position: relative,而.animateposition: absolute。正如你可能知道的,在這種情況下,html不會計算出.form-slider的高度,我必須使用JS來改變它的高度。

+0

您可以加入HTML您如何使用'納克'if'&'ng-show' –

+0

如何確定步驟和錯誤值? –

+0

錯誤附加到窗體,如果窗體不值 - 顯示錯誤。當用戶點擊下一步時,「步驟」值發生變化。 – ReasonX7

回答

0

我找到解決這個問題的唯一方法是使用removeClass | addClass事件ng-hide類:

myModule.animation('.ng-hide', function() { 
    var changeHeight = function (element) { 
    var container = element.closest('.my-selector'); 
    container.parent().height(container.height()); 
    }; 
    return { removeClass: changeHeight, addClass: changeHeight } 
}); 

不知道這是最好的解決辦法,但至少它的工作原理。


更新

我找到了更好的解決方案。當你需要使用JS計算你的頁面高度,並且你想動態更新高度時,當ng-show | ng-hide改變它的狀態。

所有你需要做的僅僅是「擴展」 ngShow & ngHide

(function() { 
    var heightDirective = ['$rootScope', '$timeout', function ($rootScope, $timeout) { 
     return { 
      restrict: 'A', 
      link: function ($scope, element, attrs) { 
       $scope.$watch(attrs.ngShow, function (newVal, oldVal) { 
        if (!angular.equals(newVal, oldVal)) { 
         $timeout(function() { 
          $rootScope.$broadcast('element:heightChange', element.height()); 
         }, 100); 
        } 
       }); 
       $timeout(function() { 
        $rootScope.$broadcast('element:heightChange', element.height()); 
       }, 500); 
      } 
     } 
    }]; 
    angular.module('mean.system').directive('ngShow', heightDirective); 
    angular.module('mean.system').directive('ngHide', heightDirective); 
    angular.module('mean.system').directive('ngIf', heightDirective); 
})(); 

然後,添加監聽到你的控制器或指令:

$rootScope.$on('element:heightChange', function() { 
    element.height(element.children().height()); 
});