我有一个 Angular/JavaScript 问题。我编写的代码有效,但我想知道为什么,因为这是我实现此代码的有根据的猜测。
代码在做什么?
用户在表单中输入文本,然后将其添加到数组并显示在屏幕上。我想确保用户不能输入空白帖子。下面的 JS 代码可以工作,但我想知道为什么。我检查了代码,并考虑了所有可能的原因,但事实并非如此。我希望有人能消除我的困惑。
我的 HTML 中的代码如下:
<form ng-submit="addPost()">
<input type="text" ng-model="title"></input>
<button type="submit">Post</button>
</form>
<div ng-repeat="post in posts">
{{post}}
</div>
我的 Controller 中的函数如下所示:
$scope.addPost = function(){
if(!$scope.title || $scope.title === '') { return false}
$scope.posts.push({title: $scope.title, upvotes: 0});
$scope.title = '';
};
一开始我只有
原始代码
$scope.addPost = function(){
if($scope.title === ' ') {return false}
$scope.posts.push({title: $scope.title, upvotes: 0});
$scope.title = '';
};
这个原始代码对我来说很有意义,但是使用这个代码,用户第一次在输入框中单击“提交”时,它显示了一个空白帖子,但在随后的尝试中却没有。
我的问题是为什么我的原始代码允许用户一次输入空白文本。据我所知,如果 $scope.title 为空白则中断函数,它应该与代码的工作方式相同。
最佳答案
您需要在表单字段上添加必填属性,这将使表单无效
标记
<form name="form" ng-submit="form.$valid && addPost(form)">
<input type="text" ng-model="title" required/>
<button type="submit">Post</button>
</form>
代码
$scope.addPost = function(){
$scope.posts.push({title: $scope.title, upvotes: 0});
$scope.title = '';
};
关于javascript - 阻止用户以 javascript/Angular 形式输入空白帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30028657/