简体   繁体   中英

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

I'm trying to write an angularjs directive that works like foundation-equalize. My problem is that I want it to work with elements that are hidden when the page loads and then appear when a user clicks something. Various combination of watch and scope settings don't seem to work for me.

My directive

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
    };
} ]);

Master html template

<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>

The equalize function I have works so I haven't included it. It gets called once, on page load, but I can't get it to be called when the show button is clicked.

As described by raina77ow no functional parenthesis should be used in the call to $watch.

This code might clarify

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

In myFunc a function is stored if you use the identifier myFunc in code it will return that function. If you on the other hand add the () it will call the function and do what ever the function does.

Another way of calling the function is this

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

This is the syntax that $watch probably uses internally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM