I have an angular/javascript question. The code I have written works but I am wondering why as it was an educated guess I took to implement this code.
What is the code doing?
User enters text into the form which is then added to an array and displayed on the screen. I want to ensure that a user cannot enter a blank post. The JS code below works, but I am wondering why. I have examined the code, and thought of all the possible reasons why this would make sense, but it just doesn't. I am hoping someone can eradicate my confusion.
The code I have in my HTML is as follows:
<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>
The function in my controller looks like this:
$scope.addPost = function(){
if(!$scope.title || $scope.title === '') { return false}
$scope.posts.push({title: $scope.title, upvotes: 0});
$scope.title = '';
};
At the beginning I only had
ORIGINAL CODE
$scope.addPost = function(){
if($scope.title === ' ') {return false}
$scope.posts.push({title: $scope.title, upvotes: 0});
$scope.title = '';
};
This original code makes sense to me, however with this code, the first time the user clicked submit in the input box it displayed a blank post, but on subsequent attempts it did not.
My question is why is my original code allowed a user to enter blank text on one occassion. As far as I can tell it should work the same as the code that works as it is saying if $scope.title is blank break the function.