如何在 AngularJS 中强制视图在加载控制器之前加载模型值?

How to force a view to load model values prior to loading controller in AngularJS?

我正在尝试从控制器自动 post 表单,而无需用户在表单上进行任何交互。我在控制器中有一个私有的 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-路由器状态配置。

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('/');
        }
    });
}]);

您可以将人口放在您定义具有 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         
}

在解析部分中的所有操作和承诺完成之前,控制器中的代码不会启动 运行。

更新:

您可以将 init 调用放入 $timeout.

$timeout(function(){
    init();
});

当然,你必须在 Controller 函数中注入 $timeout 以及其他依赖项。