【问题标题】:angularjs $watch is not getting triggered in directiveangularjs $watch 没有在指令中触发
【发布时间】:2019-05-10 13:16:23
【问题描述】:

当我使用 angularjs 1.3 及更高版本时,自定义指令 $watch 没有被触发。它适用于 angularjs 1.2。

花了很多时间,几乎所有方法都试过了,但还是不行

代码示例:

<ul class="dropdown-list-container" ng-show="isStateOpen" flexcroll="dynamic">
 <li ng-click="selectState(schoolPage.defaultState)">{schoolPage.defaultState.stateName}}</li>
</ul>

$watch 第一次被触发,之后它没有被触发 newVal 和 oldVal 是未定义的。

自定义指令:

directive('flexcroll', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, lElement, attr) {
            var parentHeight = lElement.height();
            var child = lElement.children(':eq(0)');

            scope.childHeight= function(){              
                return child.height();
            };                  
            scope.$watch(scope.childHeight, function(newVal, oldVal){
                if(attr.flexcroll=='dynamic'){
                var maxHeight = parseInt(lElement.css('max-height'));
                var childNewHeight = newVal;
                if(childNewHeight > maxHeight){
                    lElement.css({'height': maxHeight+"px"});
                } else {
                    lElement.css({'height': (childNewHeight+5)+"px"});
                }
                }
            },true);

        }
    };
})

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    试试这个scope.$parent.$apply()

    在内部运行摘要循环可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-21
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 2015-09-24
      相关资源
      最近更新 更多