简体   繁体   中英

Submit form on page load in Angular

I would like to submit a search form on page load if search terms were specified in the route. The problem is that searchForm isn't defined yet when search() runs. I've seen others get this to work by putting ng-controller right on the form element, but I have multiple forms on this page, so the controller has to be a parent of the forms.

How can I ensure the form is defined when I call search()?

myModule.controller('MyController', ['$scope', '$routeParams',
function($scope, $routeParams){
  $scope.model = {searchTerms: ""};

  $scope.search = function(){
      if($scope.searchForm.$valid){
          ...
      }
  };

  if($routeParams.terms !=""){
      $scope.model.searchTerms = $routeParams.terms;
      $scope.search();
  }
}]);

View:

<div ng-controller="MyController">
  <form name="searchForm" ng-submit="search()">
      ...
  </form>
  <form name="detailForm" ng-submit="save()">
      ...
  </form>
</div>

This seems to work:

$scope.$on('$routeChangeSuccess', function () {
    if($routeParams.terms !=""){
        $scope.model.searchTerms = $routeParams.terms;
        $scope.search();
    }
});

Have you tried just using $watch on searchForm?

if($routeParams.terms != "") {
    var unregister = $scope.$watch(function() {
        return $scope.searchForm;
    }, function() {
        // might want to wrap this an if-statement so you can wait until the proper change.
        unregister(); //stop watching
        $scope.model.searchTerms = $routeParams.terms;
        $scope.search();

    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM