2015-10-20 130 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()); 
});