我正在尝试编写一个具有以下功能的小型 Angular 应用程序:
表单以占位符文本开始为空。用户在所需的文本框中输入项目。Angular 将项目推送到集合。将表单输入重置为默认值。
我的代码看起来像这样(jsfiddle:http: //jsfiddle.net/Nn37v/1/):HTML:
<div ng-controller="MyCtrl">
<form name="talkForm">
<input ng-model="newVoice" placeholder="Say something" required />
<button ng-click="saySomething()">Say</button>
</form>
<ul>
<li ng-repeat="c in conversation">{{c}}</li>
</ul>
</div>
Javascript:
function MyCtrl($scope) {
$scope.conversation =[];
$scope.saySomething = function(){
if ($scope.talkForm.$valid){
//push to list
$scope.conversation.push($scope.newVoice);
$scope.newVoice='';
}
}
}
我面临的问题是当 $scope.newVoice='' 执行时,表单被渲染为无效,并且我会弹出有用的 HTML5 验证以鼓励我正确填写表单。显然这不是我想要的行为——用 Angular 做这件事的正确方法是什么?