AngularJs - 指令观察函数中的 if() 条件不起作用

AngularJs - if() condition in a directive observe function not working

我正在尝试根据按钮点击调整 CSS 样式的大小。这个想法是 show/hide 基于带有动画的点击的内容。有一些带有 DOM 和 Javascript 的现有代码是为此而编写的,但现在我们需要将其移至 AngularJS(我对它很陌生)。

经过反复试验,我决定对 show/hide 内容使用 ng-if,但我仍然需要设置 CSS 样式背景的高度以正确应用于扩展content(内容的长度在生产应用中是动态的)。

因此,为了设置 "max-height",我尝试在单击按钮时在 true 和 false 之间切换变量,然后将其发送到 "toggleHeight" 指令。根据指令应该将 maxHeight 设置为 scrollheight 或 null 的值。

HTML:

<div class="container" ng-controller="BaseController">
  <div ng-init "expandBox=false">
    <button ng-click="expandBox=!expandBox">Test</button>
  <br/>
    <div class="testCss" toggle-height="{{expandBox}}">
    Lorem ipsum ......

Javascript:

app.controller('BaseController', function($scope) {
    $scope.content = 'World';
})
.directive("toggleHeight",function(){
    return {
        restrict :"A",
        scope : {
            toggleHeight : "@"
        },
        link : function(scope,element,attrs){
           attrs.$observe("toggleHeight", function(value) {
               console.log("Value:",value);
               if(value) {
                   element[0].style.maxHeight=element[0].scrollHeight+"px";
                   console.log("height set to scrollHeight. value:",value);
               } else {
                   element[0].style.maxHeight="100px";
                   console.log("height is reset. value:",value);
               }
            })
         }
    };
});

CSS:

 .testCss {
   color:white;
   background-color: black;
   max-height: 100px;
   overflow: auto;
 }

但无论 "toggleHeight" 值如何,该值始终设置为 scrollHeight。打印 if-else 中变量的值表明它已被更改,但执行的代码始终来自 "true" 块。

因为我是新手,所以我似乎遗漏了一些非常明显的东西。

请注意,在 JavaScript 中,字符串 "false" 的计算结果为 truthy.

带花括号的表达式插值 ({{ }}) 将布尔值转换为字符串值。

避免对字符串以外的值使用插值:

<div class="container" ng-controller="BaseController">
  <div ng-init "expandBox=false">
    <button ng-click="expandBox=!expandBox">Test</button>
  <br/>
    ̶<̶d̶i̶v̶ ̶c̶l̶a̶s̶s̶=̶"̶t̶e̶s̶t̶C̶s̶s̶"̶ ̶t̶o̶g̶g̶l̶e̶-̶h̶e̶i̶g̶h̶t̶=̶"̶{̶{̶e̶x̶p̶a̶n̶d̶B̶o̶x̶}̶}̶"̶
    <div class="testCss" toggle-height="expandBox">
    Lorem ipsum ......

改为使用计算表达式的观察器:

app.directive("toggleHeight",function(){
    return {
        restrict :"A",
        //scope : {
        //    toggleHeight : "@"
        //},
        scope: false,
        link : function(scope,element,attrs){
           ̶a̶t̶t̶r̶s̶.̶$̶o̶b̶s̶e̶r̶v̶e̶(̶"̶t̶o̶g̶g̶l̶e̶H̶e̶i̶g̶h̶t̶"̶,̶ ̶f̶u̶n̶c̶t̶i̶o̶n̶(̶v̶a̶l̶u̶e̶)̶ ̶{̶
           scope.$watch(attrs.toggleHeight, function(value) {
               console.log("Value:",value);
               if(value) {
                   element[0].style.maxHeight=element[0].scrollHeight+"px";
                   console.log("height set to scrollHeight. value:",value);
               } else {
                   element[0].style.maxHeight="100px";
                   console.log("height is reset. value:",value);
               }
            })
         }
    };
});

此外,该指令不需要隔离作用域。