AngularJS 指令 - 链接函数元素参数在监视函数中不可用

AngularJS directive - link function element param not availble in watch function

本文关键字:函数 监视 参数 指令 链接 元素 AngularJS      更新时间:2023-09-26

我正在尝试做一些非常简单的事情:

我定义了一个指令("A"类型),当 scope 属性更改时需要操作元素。

.JS

 app.directive("autoAnimation", function ()
        {
            return {
                restrict: 'A',
                scope: {
                    animateChanged: '=',
                    maxHeight: '@'//for the first time
                },
                link: function (scope, element, attrs)
                    {
                        var isFirstTime = true;
                        scope.$watch('animateChanged', function (newVal)
                        {
                          console.log(newVal)
                                   //Trying to get the 'element' but it's not available - what can I do to get the ul element and manipulate it?
                                    //why it's not available?
                        });
                    }
            };
        });

.HTML

 <body ng-controller="MainCtrl">
   <input type="checkbox" ng-model='isChecked' />
   <ul auto-animation animate-changed='isChecked'>
     <li>Test</li>
     <li>Test</li>
     <li>Test</li>
     <li>Test</li>
     <li>Test</li>
   </ul>
  </body>

问题是当"animateChanged"被更改时,"元素"(和范围)参数不可用。

这是扑克。

我的问题:

1)为什么不可用?
2)当"animateChanged"被更改时,我该怎么做来操作"ul"元素(声明指令的位置 - 参见HTML)?

编辑

我没有检查示例,在这个示例中它是可用的(我的错,对不起)。
但是在我的项目中它不可用,我无法将示例带到我的情况中......(在我的项目中,UL 使用 ng-repeat动态构建)。知道什么可能导致这种行为吗?

它们可用,只需将手表内部更改为控制台.log(newVal,元素,范围):

console.log(newVal, element, scope)

波兰兹罗提: http://plnkr.co/edit/NZq6G04zsVBg2GgNWZkv?p=preview

当您$watch链接函数以便 (元素) 可用时,请更改为以下内容:

console.log(element);

实际上console.log(newVal)正在输出点击元素的状态,所以当checked:true/unchecked:false.