如何在角度Js中的routeparams中发送空字符串?

时间:2016-12-15 07:47:51

标签: javascript angularjs forms routeparams

您好我有一个表单,我发送searched termcategory id。它工作得很好,因为我发送的东西,但如果用户没有输入任何东西只有'类别ID'去,而在后端,如果searched term为空,所有结果都显示给用户。

但是如果我在路线参数中发送一个空字符串,我会重定向到我的index页面。这是我的app.js代码。

  when('/subcategory/:subcatId/:search', {
                templateUrl: 'partials/subcategory.html',
                controller: 'SubCategoriesController'
            }).

我的表格

   <form name="searchCategoryForm">
                <div class="col-md-9 col-xs-10 col-sm-10">
                    <input class="form-control" placeholder="Find your item here...." ng-model="search" type="text" style="color:#09669c;">
                </div>
                <div class="col-md-2 col-xs-2 col-sm-2">
                    <a class="btn btn-primary" role="button" href='#/subcategory/{{cats[clicked_category].id}}/{{search}}'> Search</a>                  
                </div>
            </form>

我的controller.js

$scope.search_term = $routeParams.search;
    $scope.category_id = $routeParams.subcatId;

    /* Search category form */


    $scope.search_category = function () {
        $http({
            method: 'GET',
            url: 'abc',
            params: {"name": $scope.search_term, "category_id": $scope.category_id},
            headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': $rootScope.keyword_auth_token}
        })
                .success(function (data) {
                    $scope.search_category_result = data.items;
                    console.log($scope.search_category_result);
                    })
                .error(function (data) {
                    console.log(data);
                });
    };
    /* Search category form ends here*/
    if ($scope.search_term && $scope.category_id)
    {
        $scope.search_category();
    }

1 个答案:

答案 0 :(得分:1)

我相信您应该将搜索字词标记为可选,并在后面加上问号(?):

when('/subcategory/:subcatId/:search?', {
    templateUrl: 'partials/subcategory.html',
    controller: 'SubCategoriesController'
}).

有关详细信息,请参阅此答案:Can angularjs routes have optional parameter values?