[英]AngularJS directive - link function element param not availble in watch function
我正在嘗試做一些非常簡單的事情:
我定義了一個指令('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”更改時,“ element”(和范圍)參數不可用。
這是the 子 。
我的問題:
1)為什么不可用?
2)當更改“ animateChanged”時,我該怎么做以操縱“ ul”元素(在其中聲明了指令-請參見HTML)?
編輯
我沒有檢查示例,但在此示例中可用(我不好,對不起)。
但是在我的項目中它不可用,因此我無法將示例應用於我的情況...(在我的項目中,UL使用ng-repeat動態構建)。 任何想法可能導致這種行為嗎?
它們可用,只需將手表內部更改為console.log(newVal,element,scope):
console.log(newVal, element, scope)
網址: http ://plnkr.co/edit/NZq6G04zsVBg2GgNWZkv?p = preview
當您在$watch
watching中使用鏈接函數以使(element)可用時,請更改為:
console.log(element);
實際上console.log(newVal)
正在輸出clicked元素的狀態,因此console.log(newVal)
時checked:true/unchecked:false
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.