簡體   English   中英

在Angular頁面加載時提交表單

[英]Submit form on page load in Angular

如果路線中指定了搜索字詞,我想在頁面加載時提交搜索表單。 問題是當search()運行時還沒有定義searchForm 我已經看到其他人可以通過將ng-controller放在form元素上來使其工作,但是我在此頁面上有多個表單,因此控制器必須是這些表單的父級。

調用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();
  }
}]);

視圖:

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

這似乎可行:

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

您是否嘗試過僅在searchForm上使用$watch

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

    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM