2

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>
1

2 Answers 2

2

This seems to work:

$scope.$on('$routeChangeSuccess', function () {
    if($routeParams.terms !=""){
        $scope.model.searchTerms = $routeParams.terms;
        $scope.search();
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

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();

    });
}

1 Comment

Thanks, but if I have multiple forms I'd rather not need multiple watches. I posted a solution that seems to do the trick.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.