[英]AngularJS directive - link function element param not availble in watch function
I'm trying to do something very simple: 我正在尝试做一些非常简单的事情:
I defined a directive ('A' type) that need to manipulate the element when the scope property changed. 我定义了一个指令('A'类型),当scope属性更改时,该指令需要操纵该元素。
JS 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 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>
The problem is when the 'animateChanged' is changed, the 'element' (and scope) parameter are not available. 问题是当“ animateChanged”更改时,“ element”(和范围)参数不可用。
Here is the plunker . 这是the 子 。
My questions: 我的问题:
1) why it's not available? 1)为什么不可用?
2) what can I do to manipulate the 'ul' element (where the directive is declared - see the HTML) when 'animateChanged' is changed? 2)当更改“ animateChanged”时,我该怎么做以操纵“ ul”元素(在其中声明了指令-请参见HTML)?
EDIT 编辑
I didn't check the example, and in this example it's available (my bad, sorry). 我没有检查示例,但在此示例中可用(我不好,对不起)。
but in my project it's not available, and I can't bring the example to my situation... (in my project the UL build dynamically with ng-repeat). 但是在我的项目中它不可用,因此我无法将示例应用于我的情况...(在我的项目中,UL使用ng-repeat动态构建)。 Any idea what can possibly cause to this behavior?
任何想法可能导致这种行为吗?
They are available, just change the inside of your watch to console.log(newVal, element, scope): 它们可用,只需将手表内部更改为console.log(newVal,element,scope):
console.log(newVal, element, scope)
Plnkr: http://plnkr.co/edit/NZq6G04zsVBg2GgNWZkv?p=preview 网址: http ://plnkr.co/edit/NZq6G04zsVBg2GgNWZkv?p = preview
As you are $watch
ing in a link function so that (element) is available, change to this: 当您在
$watch
watching中使用链接函数以使(element)可用时,请更改为:
console.log(element);
actually console.log(newVal)
was outputting the state of the clicked element so when checked:true/unchecked:false
. 实际上
console.log(newVal)
正在输出clicked元素的状态,因此console.log(newVal)
时checked:true/unchecked:false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.