Search code examples
javascriptangularjsformsangularjs-scopeonload

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>

Solution

  • This seems to work:

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