0

我有一个类似“谷歌搜索”的页面,显示后端返回的项目列表。

在页面中有一个包含许多不同字段的 HTML 表单。用户可以更改这些字段中的一个或多个值,然后后端将返回新的相关项目列表。

其中一个请求是让用户能够打开过滤结果的直接链接,到目前为止,这是通过 url 中的查询参数完成的,但现在我想将此页面更改为与 angularjs 异步工作。假设该过滤器表单中的字段可以不时更改。

那么毕竟,在 angularjs 中处理复杂表单并允许表单的 get 方法的最佳方法是什么?

4

2 回答 2

0

您始终可以在您的范围内构建一个 URL 以响应用户所做的任何事情,然后执行类似的操作<a ng-attr-href="{{view.userURL}}" target="_blank">{{view.userURL}}</a>

于 2014-08-20T16:03:52.230 回答
0

经过一番思考,我得到了解决方案。

这里的一些“魔法”是在 $scope 中有一个对象(名为 $scope.filter)来保存所有表单输入值,因此它很容易使用,并且不需要对如果向表单中添加了新输入,则为控制器。

    angular.module('myApp')

    .controller('myController', ['$scope', '$http' '$location', function($scope, $http, $location) {
        $scope.filter = {};

        $scope.init = function(){
            // $location.search() will return an object with the params,
            // those values are set to $scope.filter, and the filter values are initialized in case of direct link to the page
            $scope.filter = $location.search();

            $scope.executeFilter();
        };

        // doing the job of fetching the data I want to present,
        // using the filter values as a Json in that server call
        $scope.executeFilter = function(){
            // making sure to update the url with the current filter values,
            // so the user is able to copy the relevant url for a later use
            $location.search($scope.filter);

            var paramsAsJson = angular.toJson($location.search());

            $http.post('my-url', paramsAsJson).success(function(data) {
                // update view
            });
        };

        $scope.init();


    }]);

这是一个示例视图:

<form ng-submit="executeFilter()">
    <input name="some_text" type="text" ng-model="filter.some_text">
    <!-- more inputs here -->

    // it will work even with multiple select
    // (will pass to the server a json with array of selected values)
    <select multiple="multiple" name="some_options" ng-model="filter.some_options">
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
    </select>   
    <button>Filter</button>
</form>

因此,现在如果用户尝试使用这样的 url 打开此页面,则在页面加载后,www.my-url.com/?some_text=foo带有指令的输入ng-model="filter.some_text"将包含“foo”,并且将发出带有该参数的服务器请求。

于 2014-08-21T08:56:50.073 回答