【问题标题】:Submit form on page load in Angular在 Angular 中的页面加载时提交表单
【发布时间】:2014-10-09 13:36:30
【问题描述】:

如果在路由中指定了搜索词,我想在页面加载时提交搜索表单。问题是searchFormsearch() 运行时尚未定义。我已经看到其他人通过将 ng-controller 放在表单元素上来实现此功能,但我在此页面上有多个表单,因此控制器必须是表单的父级。

如何确保在调用 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>

【问题讨论】:

标签: javascript angularjs forms angularjs-scope onload


【解决方案1】:

这似乎有效:

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

【讨论】:

    【解决方案2】:

    您是否尝试过在 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();
    
        });
    }
    

    【讨论】:

    • 谢谢,但如果我有多个表格,我宁愿不需要多个手表。我发布了一个似乎可以解决问题的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 2018-04-10
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多