我正在尝试从控制器自动发布表单而不在表单上进行任何用户交互。我在控制器中有一个私有init()函数,触发表单上的按钮单击。 但隐藏的表单字段尚未获得值。如何确保隐藏字段在表单提交之前填充值?
感谢您提出任何建议。
<div>
<form name="myForm" method="post" action="@Model.Settings["URL"]" ng-controller="MyCtrl">
<input type="hidden" name="userid" value="{{UserSettings.Settings.UserId}}">
<input type="hidden" name="amount" value="{{Payment.Amount}}">
<button id="payButton" type="submit" class="action blue"><span class="label">Pay</span></button>
<script language="javascript">
var UserSettings = (function (o) {
return o;
})(@Html.Raw(JsonConvert.SerializeObject(@Model)));
</script>
</form>
</div>
myControllers.controller('MyCtrl', ['$scope', '$state', '$element', 'dataService',
function ($scope, $state, $element, service) {
$scope.Payment = service.GetPayment());
$scope.UserSettings = UserSettings;
function init() {
// How can I force to have values in the hidden form fields before the button click that submits the form ?
$element.find('#payButton').trigger("click");
};
init();
}]);
这是ui-router状态配置。
var app = angular.module('pay', ['ui.router', 'pay.controllers', 'pay.services', 'exceptionOverride', 'ngSanitize']);
app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('home', {
url: '/' ,
templateUrl: 'search'
})
.state('payment', {
url: '/payment',
templateUrl: 'Payment'
});
//setting html5 removes the # from URL but causes routing problems at the moment.
//$locationProvider.html5Mode(true);
$urlRouterProvider.rule(function ($injector, $location) {
//what this function returns will be set as the $location.url
var path = $location.path(), normalized = path.toLowerCase();
if (path != normalized) {
$location.replace().path(normalized);
}
else if (path == '') {
$location.path('/');
}
});
}]);
答案 0 :(得分:2)
您可以将人口放在您定义具有MyCtrl
状态的点上,如下所示:
.state('myState', {
// ...
resolve: {
Payment: ['dataService', function (dataService) {
return dataService.GetPayment();
}],
// Same for other objects needed
}
})
然后在你的控制器中:
myControllers.controller('MyCtrl', ['$scope', '$state', '$element', 'Payment',
function ($scope, $state, $element, Payment) {
$scope.Payment = Payment;
// Same for other objects needed
// Rest code
}
在解析部分中的所有操作和承诺完成之前,Controller中的代码不会开始运行。
更新
您可以将init
来电置于$timeout
。
$timeout(function(){
init();
});
当然,您必须在Controller函数中注入$timeout
以及其他依赖项。