我正在尝试编写一个像 Foundation-equalize 一样工作的 angularjs 指令。我的问题是我希望它能够处理页面加载时隐藏的元素,然后在用户单击某些内容时显示的元素。 watch 和示波器设置的各种组合似乎对我不起作用。
我的指令
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>
包含.html
<div class="row" data-mm-equalize="">
<!-- divs to be equalized go here -->
</div>
我的均衡功能有效,所以我没有包含它。它在页面加载时被调用一次,但是当单击显示按钮时我无法调用它。
最佳答案
正如 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 可能在内部使用的语法。
关于javascript - 当元素在 angularjs 中显示或隐藏时,如何在指令中获取监视函数来触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24405742/