【发布时间】:2019-04-22 08:48:15
【问题描述】:
我正在尝试更新基于 $http 响应的单击按钮值。我想在使用 ng-click 功能发出 $http 请求时将按钮值更改为 Processing...。并且根据 Success/Error 响应,需要更新文本 Success 和 Try Again 等。
我正在使用 ui-router 并且我有不同的表单元素分布在不同的状态,例如邮箱、用户名、密码等
在我看来,我在电子邮件状态下跟踪代码。
<div ng-controller="RegisterEmailController">
<div class="form-group" style="position: relative;" ng-class="{ 'has-error': form.useremail.$dirty && form.useremail.$error.required && form.useremail.$invalid }">
<input type="email" name="useremail" id="useremail" ng-model="RegisterEmailController.userDetail.useremail" ng-required="true">
<span ng-show="form.useremail.$dirty && form.useremail.$error.required" class="help-block text-sm text-danger pl-4">Oops! Incorrect email address, or field is empty</span>
<span ng-hide="form.useremail.$dirty && form.useremail.$error.required" class="help-block d-block text-sm text-danger px-4">{{ErrorMsg}}</span>
</div>
<button type="button" ng-click="RegisterEmailController.nexStep()">{{buttonTxt}}</button>
</div>
在我的控制器中
var controller = this;
$scope.buttonTxt = 'Next Step';
controller.nexStep = function() {
$scope.buttonTxt = 'Processing...';
if ( validation_conditions ) {
$http({
method: "POST",
url: ApiURL,
headers: { "Content-Type": "application/json" },
data: getData
}).then(function success(response) {
$scope.buttonTxt = 'Success';
}, function error(response) {
$scope.buttonTxt = 'Try Again';
return;
});
} else {
$scope.buttonTxt = 'Try Again';
return;
}
}
使用上面的代码,我无法在单击时更改按钮文本,我也尝试使用controller.buttonTxt,但它在初始化时根本不打印值。我也尝试了 ng-bind 指令,但没有成功。
请在我做错的地方帮助我。据我估计,$scope 可能与控制器中的this (var controller = this;) 冲突。
另外,如何根据响应向输入父元素添加成功/错误类?
感谢您阅读我的查询,并提前感谢您的帮助。
【问题讨论】:
-
不使用$scope时需要在
ng-controller中分配控制器别名 -
你能用代码做一个 plunkr 吗?
-
感谢@charlietfl,通过分配控制器别名,我的问题得到了解决,但还需要解决更多问题。
标签: javascript angularjs