【问题标题】:Angularjs form submission and navigation to other page [closed]Angularjs表单提交和导航到其他页面[关闭]
【发布时间】:2016-02-08 02:57:23
【问题描述】:

我有一个索引页面,其中有一个带有文本字段和搜索按钮的表单。当用户点击搜索按钮时,表单需要获取文本字段的值并使用get方法导航到搜索页面。这样搜索内容就会显示在搜索页面的url中。 我需要使用 angularjs 来完成。

请给我一个方法或给我一个整体的想法它是如何工作的。

【问题讨论】:

    标签: javascript html angularjs forms


    【解决方案1】:

    如果您使用的网站没有阻止跨域请求,那么您可以执行以下操作(实时预览http://codepen.io/larryjoelane/pen/WraEOY):

    HTML:

        <h1>Submit To Search Engine On Key Up</h1>
    <div ng-app="myApp" ng-controller="myCtrl">
      <form>
        Search:
        <input type="text" ng-model="keyword" ng-keyup="search()">
      </form>
    
      <div ng-bind="results"></div>
    
    </div>
    

    Angular/JavaScript

     var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
    
      //you can change the value of this to someting else like
      //search.html?search=  if you want
      var url = "https://www.google.com/?gws_rd=ssl#safe=active&q=";
    
    $scope.search = function(){
      $http.get(url + $scope.keyword)
        .then(function(response) {
          $scope.results = response;
        }, function(response) {
          $scope.results = "Something went wrong";
        });
    
    
    };
    
    });
    

    或者如果您希望它在不使用 $http 函数的情况下将您的 get 变量汇总到另一个页面,正如 Kaveh 建议的那样,您可以将您的控制器更改为以下代码:

    HTML:

        <h1>Submit input as http variable(GET) to another page</h1>
    <div ng-app="myApp" ng-controller="myCtrl">
      <form>
        Search:
        <input type="text" ng-model="keyword">
        <input type= "button" value ="search" ng-click="search();">
      </form>
    
      <div ng-bind="results"></div>
    
    </div>
    

    Angular/JavaScript

     var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
    
      //you can change the value of this to someting else like
      //search.html?search=  if you want
      var url = "search.html?search=";
    
    $scope.search = function(){
    
    
       //navigate to another page using keyword model variable
       window.location = url + $scope.keyword;
    
    
    };
    
    });
    

    【讨论】:

    • 为什么不直接改变窗口位置? window.location="https://www.google.com/?gws_rd=ssl#safe=active&amp;q=" + $scope.keyword
    • 非常感谢。但我想使用文本字段的值导航到名为“search.html”的其他页面。我该怎么做?
    • 查看我的答案中的替代解决方案,它应该能够帮助您完成您想要完成的工作。
    【解决方案2】:

    我认为您可以使用ui-router 模块并使用ui-sref 导航到通过搜索字段关键字的搜索页面。

    这里是 API 参考 UI-Router

    <a ui-sref="pages.search({ search: keyword })" class="btn btn-primary"></a>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-31
      • 2013-10-26
      • 2018-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多