gpt4 book ai didi

javascript - Angular : Show and hide class on ng-click

转载 作者:行者123 更新时间:2023-11-30 07:13:56 24 4
gpt4 key购买 nike

我正在使用 AngularJS 开发一个网站。我有一个故意设置为“display:none”的表单。

我有一个显示创建的按钮。我想要的是,当我点击创建按钮时,设置为“display:none”的表单应该更改为“display:block”并且创建按钮应该隐藏。

提交表单后,表单应该隐藏,创建按钮应该再次可见。

P.S:现在我知道有几种方法可以做到这一点,比如我可以使用 ng-show 或 ng-hide 指令。或者我可以使用 ng-click 指令。我想知道在开发严肃而专业的 Web 应用程序时,这种情况下的最佳编程实践是什么。

这是一件简单的事情,所以如果你能提供代码就太好了。

最佳答案

只需使用 ngClick指令与 ngShow指令见下面的工作示例:

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

myApp.controller('FormController', ['$scope',
function($scope) {

// init showForm to false;
$scope.showForm = false;

// init empty user object for our form
$scope.user = {};

$scope.submitForm = function() {
// logic when the form is submitted
//...

// reset the user
$scope.user = {};

// finally hide the form
$scope.showForm = false;
};

}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">

<div ng-controller="FormController">

<button ng-hide="showForm" ng-click="showForm = true">Show form</button>

<form ng-show="showForm" ng-submit="submitForm()">

<input type="text" name="firstname" ng-model="user.firstname" />

<input type="submit" value="submit" />

</form>

</div>

</div>

如果 showForm 为真,我们将设置表单以显示。

此变量是使用 button 元素上的 ngClick 指令切换的,并且还在 Controller 的 submitForm 函数中明确设置为 false。

我们使用 ngSubmit指令将 submitForm() 绑定(bind)到 onsubmit 事件。提交表单后,您运行逻辑,然后重置并隐藏表单。

关于javascript - Angular : Show and hide class on ng-click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36820413/

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