我曾经广泛使用 Jquery。现在我偶然发现了 Angularjs,我正在尝试了解它是如何工作的,并且我对 AutoMagic 的工作方式感到非常兴奋。例如,我可以通过使用 ng-click
、ng-hide
和 ng-show
来完成以下隐藏和显示几个 block 的过程>。
<form id="signup-form" ng-submit="processForm()" ng-hide="showConfirm" >
<input type="text" name="user" ng-model="name">
<button type="submit" id="submit" ng-click="showConfirm = ! showConfirm">Submit</button>
</form>
<div class="col-md-12 confirmation" ng-show="showConfirm">
<h2 >Thanks alot for your feedback.</h1>
</div>
但是,我仍然想知道如何从代码(例如 Controller )中执行相同的操作。在 Jquery 中,一种方法是:
$( "#submit" ).click(function() {
$(".confirmation").show();
$("#signup-form").hide();
});
也许如果我想验证表单,我可以在 Jquery 中使用 .preventDefault();
并执行某些操作。这一切在 AngularJs 中是如何工作的?
最佳答案
只需更改 Controller 中的模型值:showConfirm = !showConfirm;
这将使用您已有的 ng-hide
和 ng-show
指令自动更新您的 View 。
更好的是,调用作用域函数,例如:
$scope.toggleConfirm = function() { showConfirm = !showConfirm; }
...并使用 ng-click="toggleConfirm()"
在您的 View 中调用它以保留您的代码 DRY .
关于javascript - 如何通过 js 代码显示/隐藏点击事件上的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26166498/