我希望在成功保存表单后将表单按钮的文本从“保存”更改为“已保存”。
<form name="myForm" ng-submit="saveForm()">
<!-- some input text fields here -->
<button type="submit">{{buttonText}}</button>
</form>
控制器:
$scope.buttonText = 'Save';
$scope.saveForm = function() {
//save operation here
$scope.buttonText = 'Saved';
$scope.myForm.$setPristine();
};
这是完美的工作但是当用户更改表单中的值以再次保存时,如何将按钮重置为“保存”?我想到的一种可能性是关注原始状态,但我认为有更好的解决方案吗?
答案 0 :(得分:0)
例如,您可以在范围属性上添加自定义监视,当其中一个更改时,您可以重置按钮的文本。
<form name="myForm" ng-submit="saveForm()">
<input type="text" ng-model="foo" />
<button type="submit">{{buttonText}}</button>
</form>
$scope.$watch('foo', function(){
$scope.buttonText = 'save';
});
你也可以在每个输入上使用ng-change来调用一个重置文本的函数,但不会有我的偏好,因为它会降低我的可维护性成本。另一方面,手表可能有点贵。
为了使手表更容易,您应该将模型属性嵌套在一个对象上并使用$ watchCollection(自1.2起)
答案 1 :(得分:0)
您可以在表单项上使用ng-change事件处理程序,并在那里修改按钮的状态。
<form name="myForm" ng-submit="saveForm()">
<input type="text" ng-model="foo" ng-change="formChanged()" />
<button type="submit">{{buttonText}}</button>
</form>
并在您的控制器中:
$scope.formChanged= function() {
$scope.buttonText = 'Save';
//any other logic necessary
};
这比使用手表要轻得多,你可以对你采取的行动更加明智(例如,如果它恢复到原始价值,会发生什么变化)
答案 2 :(得分:0)
您可以在输入字段中调用ng-change并编写一个函数以重新设置它。
<input type="text" ng-model="foo" ng-change="buttonText ='save'"/>