gpt4 book ai didi

javascript - Angular js 中的重置按钮实现

转载 作者:行者123 更新时间:2023-11-28 18:50:32 24 4
gpt4 key购买 nike

我想知道 Controller 函数中$scope.reset();的用途是什么?重置似乎在没有此代码的情况下也可以工作,但文档说使用此代码,我不明白为什么:

 <body ng-app="myapp" ng-controller="resetController">
<label>Enter name</label><input type="text" ng-model="name"/>
<label>Enter emailid</label><input type="text" ng-model="email"/>
<button ng-click="reset()">Reset</button>
<script>
angular.module("myapp",[])
.controller("resetController", function($scope)
{
$scope.reset = function()
{
$scope.name = "";
$scope.email = "";
}
$scope.reset(); /* not sure why we need this */
});
</script>
</body>

最佳答案

<body ng-app="myapp" ng-controller="resetController">
<label>Enter name</label><input type="text" ng-model="name"/>
<label>Enter emailid</label><input type="text" ng-model="email"/>
<button ng-click="reset()">Reset</button>
<script>
angular.module("myapp",[])
.controller("resetController", function($scope)
{
$scope.reset = function()
{
$scope.name = "";
$scope.email = "";
}
$scope.reset(); /* not sure why we need this */
});
</script>
</body>

这是你的代码。现在看,您有 ng-click="reset()"。这是在 Controller 内调用 $scope.reset 方法,因此字段被清除。

正如您想知道的那样:$scope.reset();/* 不确定为什么我们需要这个*/

不,您不需要这个,除非您不从您的 Angular 调用此方法。 $scope.reset() 在 Controller 内部使用,当您需要在页面加载事件上调用方法时。

* 我认为 $scope.reset() 可用于在页面首次加载时清除字段。

关于javascript - Angular js 中的重置按钮实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34543720/

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