簡體   English   中英

如何在angularjs中顯示或隱藏元素時在指令中獲取監視函數以激發

[英]How do I get a watch function in a directive to fire when elements are shown or hidden in angularjs

我正在嘗試寫一個angularjs指令,它的工作方式類似於Foundation-equalize。 我的問題是我希望它與在頁面加載時隱藏並在用戶單擊某些內容時顯示的元素一起使用。 監視和范圍設置的各種組合似乎對我不起作用。

我的指令

myApp.directive("mmEqualize", [ function() {
    function link(scope, element, attrs) {
        function equalize() {
            // my equalize function that only gets called on page load
        }
        // Even this most generic does not work
        scope.$watch(equalize());
    }
    return {
        restrict: 'A',
        link : link
    };
} ]);

主html模板

<div data-ng-show="someFlag">
    <div ng-include src="'included.html'"></div>    
</div>
    <button data-ng-click="someFlag = true">Show</button>

included.html

<div class="row" data-mm-equalize="">
    <!-- divs to be equalized go here -->
</div>

我擁有的equalize函數有效,因此未包含在內。 它在頁面加載時被調用一次,但是當單擊顯示按鈕時我無法調用它。

如raina77ow所述,在$ watch的調用中不應使用功能括號。

這段代碼可能會澄清

var myFunc = function () {
  return "string";
};
console.log(myFunc); // Will log the functions code
console.log(myFunc()); // Will log the return from the function

如果在代碼中使用標識符myFunc,則會在myFunc中存儲一個函數,它將返回該函數。 另一方面,如果添加(),它將調用該函數並執行該函數所做的任何事情。

調用該函數的另一種方式是

console.log(myFunc.call()); // Will log the return from the function, () == .call()

這是$ watch內部可能使用的語法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM