【问题标题】:AngularJS directive - link function element param not availble in watch functionAngularJS 指令 - 链接函数元素参数在监视函数中不可用
【发布时间】:2015-01-11 21:03:12
【问题描述】:

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

我定义了一个指令('A' 类型),当作用域属性发生变化时,它需要操纵元素。

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' 改变时,'element'(和范围)参数不可用。

这里是plunker

我的问题:

1) 为什么它不可用?
2) 当 'animateChanged' 改变时,我能做些什么来操作 'ul' 元素(指令被声明的地方 - 见 HTML)?

编辑

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

【问题讨论】:

标签: javascript angularjs angularjs-directive watch


【解决方案1】:

当您在链接函数中$watching 以便 (element) 可用时,更改为:

console.log(element);

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

【讨论】:

  • 你是对的!!但它在我的项目中可用(这只是一个测试)也许我项目中的其他事情导致了这个问题......
  • 你到底想做什么?你想在复选框被选中/取消选中时执行某些操作,比如显示/隐藏吗?
【解决方案2】:

它们是可用的,只需将手表内部更改为 console.log(newVal, element, scope):

console.log(newVal, element, scope)

Plnkr:http://plnkr.co/edit/NZq6G04zsVBg2GgNWZkv?p=preview

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 1970-01-01
    • 2015-03-28
    • 2013-06-10
    • 2014-07-05
    • 2014-03-11
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    相关资源
    最近更新 更多