gpt4 book ai didi

javascript - 如何在父级上使用 ng-show 制作指令以触发 show 上的功能

转载 作者:行者123 更新时间:2023-11-28 04:01:30 28 4
gpt4 key购买 nike

我有一个带有 ng-show 的 div。这个 div 是我创建的自定义指令的包装器。

HTML

<div ng-show="mycondition">
<div my-directive></div>
</div>

JS

function myDirective() {
function doSomthing() {...}
}
angular.module('myapp').directive('myDirective', myDirective);

我希望指令做某事,只有在 ng-hide 类从包装器 div 中删除后(换句话说,仅“显示”)我怎样才能做到这一点?

谢谢!

最佳答案

有趣!这是我想解决这个问题的方法:

我会像这样添加 ng-show:

ng-show="mycondition && doSomething()"

现在,只要您的条件满足,只要 ng-show 为真,它就会调用 doSomething 函数。

很酷,让我们将此函数添加到 myDirective 中,我们将在函数内的 console.log 中了解它是否被调用。像这样:

app.directive("myDirective", function() {
return {
restrict: "A",
scope: {
doSomething: "="
},
template: "<h5>inside myDirective!</h5>",
controller: function($scope) {
$scope.doSomething = function() {
console.log("myDirective doing something");
return true; // Important, this function being a condition of ng-show needs to return true
}
}
};
});

现在,最后,让我们调用我们的指令:

<div ng-show="mycondition && doSomething()">
<div my-directive do-something="doSomething"></div>
</div>

在下面找到工作片段。此外,还有一个切换按钮可以切换 mycondition 以演示它在 true 时被调用。

注意事项

  • 使用这种方式,函数需要返回 true 因为它是我们 ng-show
  • 的条件
  • 由于摘要循环,函数被多次调用。但是我们可以通过在 myDirective 范围内设置一个私有(private)变量来摆脱这种行为,该变量在访问时设置为 true;在 true 时阻止输入,并在工作完成时设置为 false

var app = angular.module("myApp", []);

app.controller("appCtrl", function($scope) {
$scope.mycondition = true;
$scope.changeCondition = function() {
$scope.mycondition = !$scope.mycondition;
}
});

app.directive("myDirective", function() {
return {
restrict: "A",
scope: {
doSomething: "="
},
template: "<h5>inside myDirective!</h5>",
controller: function($scope) {
$scope.doSomething = function() {
console.log("myDirective doing something");
return true;
}
}
};
});
<!DOCTYPE html>
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body ng-controller="appCtrl">
<button ng-click="changeCondition()">toggle</button>
<div ng-show="mycondition && doSomething()">
<div my-directive do-something="doSomething"></div>
</div>

</body>

</html>

关于javascript - 如何在父级上使用 ng-show 制作指令以触发 show 上的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43186843/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com