Angular如何在搜索和结果视图之间切换并传递数据

时间:2014-12-02 07:54:30

标签: javascript angularjs web-services

所以我尝试做以下事情,我确信这是非常常见的,但没有遇到过这个例子。

查看1和控制器1:

使用带有ng-model =“searchTerm”和ngSubmit事件的文本框创建一个简单视图。 Web服务受到搜索词的影响,并希望在下一个屏幕上显示结果。

查看2和控制器2

当用户点击提交视图更改到结果屏幕时,将显示来自Web服务的结果。

1)使用路由和更改视图,以这种方式直观地更改屏幕的常规方法是什么?或者使用ng-show / ng-hide?

2)如何将搜索词从控制器1传递给控制器​​2?

3 个答案:

答案 0 :(得分:0)

这将是这样的(我没有测试过这个):

查看1和控制器1:

查看:

<form ng-submit="showResults(searchTerm)">
    <input type="text" ng-model="searchTerm">
</form>

控制器:

$scope.showResults = function (searchTerm) {
     // just redirect, the second page will take care of making the query
     // make sure to inject $location into your controller
     $location.url('/results?q=' + encodeURIComponent(searchTerm));
});

查看2和控制器2:

我假设这个视图是为路由/results定义的。

控制器:

app.controller('SearchResultsCtrl', ['$scope', '$location', '$http', function ($scope, $location, $http) {
    // watch the query string parameter for changes, so you can update it 
    // and have the query re-run.
    $scope.$watch(function () {
        return ($location.search() || {}).q;
    }, function (searchTerm) {
        // make webservice call using $http or whatever, e.g.
        $http.get('/api/search?q=' + searchTerm).then(function (data) {
            $scope.results = data;
        });
    });
 }]);

然后,只需在视图中使用results范围属性即可。

答案 1 :(得分:0)

1.Routing将导致您的页面发生变化,它将涉及客户端 - 服务器交互。如果您对带宽有约束,这可能会导致开销。 ng-show和ng-hide只会切换已经存在的页面的显示,基本上它将是一个页面。所以你需要根据需要选择。

2.答案取决于您希望您的应用程序做什么。您的应用程序是否需要存储您所搜索的搜索字符串?如果是的话,我们可以将它们存储在服务中。但是,这不会在会话中存储您的值。

此外,我们可以将其作为GregL附加到URL中,如评论中所述,在多次搜索命中的情况下不会存储字符串。假设你想在进行任何搜索之前知道你搜索了什么,在这种情况下,将它附加到routeParams和其他URL参数将变得笨拙地处理。在这种情况下,我建议你使用服务。但是存储和以前的值对你来说并不重要,你只需使用routeParam即可。

答案 2 :(得分:0)

使用搜索功能的最常见和最正确的方法是搜索查询由URL中的相应GET参数反映。在旧学校网站和单页应用程序中也是如此。我们的想法是,结果屏幕必须与当前搜索字词相对应,当然可以加入书签。

为此,您可以使用ngRoute模块,该模块允许您设置简单的路由系统。

以下是一些基本示例:

// Configure routes
app.config(function($routeProvider) {
    $routeProvider.when('/home', {
        controller: 'HomeController',
        templateUrl: 'home.html'
    })
    .when('/search-results', {
        controller: 'SearchResultsController',
        templateUrl: 'results.html'
    })
    .otherwise('/home');
});

// This controller will handle form submission and redirect to search controller
app.controller('HomeController', function($scope, $location) {
    $scope.search = function() {
        $location.path('/search-results').search({query: $scope.query});
    };
});

// This controller takes search query from the URL and uses it to make search request
app.controller('SearchResultsController', function($scope, $routeParams, $location) {
    $scope.query = $routeParams.query;
    $scope.url   = $location.absUrl();

    // load search result with some GET request using $scope.query term
});

简单演示:http://plnkr.co/edit/FMRTTbxdNv0pGSYpfwve?p=preview