form ng-submit 加载一个子视图,但只加载一次

form ng-submit loads a sub-view, but only once

所以基本上我有一个网页 'Index',它有一个表单和一个 ng-view 部分。
所以我想要的是让用户填写表单中的一些字段并提交,ng-view 呈现在表单下方,其中包含服务器行程的结果。

而且有效!当此视图加载时,它会使用从表单填写的值、returns 数据访问服务器并将其呈现到页面。

我遇到的问题是这只能使用一次。

填写表格,点击提交,下面会加载结果页面。 更改表单中的值并再次提交,它不会将查询发送回服务器。

谁能告诉我哪里错了?
这是我的第一个 angular 应用程序,我一直在想办法解决问题 - 所以我什至不确定这是公认的做事方式。

奖金问题:谁能告诉我为什么当 *//$routeProvider.when('/', {templateUrl: '/Reports/Index' });* 行取消注释时我的整个浏览器崩溃?

这是所有相关代码:

//The main index page.
<div ng-app="ReportsApp" ng-controller="indexFormsCtrl" class="form-inline">

    <!-- Our main input form -->
    <form ng-submit="search()">
        <input type="text" ng-model="mySearchField" />
        <input class="btn btn-primary" type="submit" value="Search" />
    </form>

    <div class="container">
        <div ng-view></div>
    </div>
</div>

//Main routing secion
angular.module('ReportsApp', ['ReportsApp.ctrl.bonus', 'ReportsApp.ctrl.index', 'ngRoute'])
    .config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {

        //When this is present it will make the page crash - like it is stuck in an infinite loop
        //commented out the site works, but it redirects me to /squiffy
        //$routeProvider.when('/', {
            //templateUrl: '/Reports/Index',
        //});
        $routeProvider.when('/MyReport', {
            templateUrl: '/Reports/MyReport',
            controller: 'myReportCtrl',
        });
        $routeProvider.otherwise({
            redirectTo: '/squiffy'
        });
        $locationProvider.html5Mode(false).hashPrefix('!');
    }])

//The index controller - not much to see other than the location.path redirect.
angular.module('ReportsApp.ctrl.index', []).controller('indexFormsCtrl', function ($scope, $location, reportsService) {
    $scope.mySearchField = '';

    $scope.search = function()
    {
        reportsService.mySearchField = $scope.toDate;
        //redirect the view to MyReport
        $location.path('MyReport')
    }
});

//the report contents controller (ng-view controller). Hits the server, gets some json, stores it in $scope
angular.module('ReportsApp.ctrl.bonus', []).controller('myReportCtrl', function ($scope, $http, $location, reportsService) {
    $scope.myModel = null;
    getTheReportData(reportsService);
    //Get the bonus overview
    function getTheReportData(reportsService) {
        alert('searching');
        $scope.myModel = GetDataFromServer(reportsService.mySearchField);
    };
});

我假设这是因为控制器初始化时加载了数据。而且它只会在页面首次加载时初始化,而不会在后续提交时初始化。

您的视图未重新加载的原因是 $location 进行了一些优化。如果路径没有改变,页面将不会重新加载。解决这个问题的方法是使用

$route.reload();

但是您的代码还可以使用更多组织...与其将服务器请求绑定到加载控制器,不如将服务器请求代码移动到您的搜索功能?更好的是,您可以创建一个服务来处理可在每个控制器中重复使用的 HTTP 请求。详细了解 angular 服务 here

关于您的第二个问题:当您取消对该行的注释时,您的浏览器会崩溃,因为您传递给 $routeProvider 的路由对象需要一个控制器。

您的路线应如下所示,但请将 'controllerName' 替换为您的实际控制器。

$routeProvider.when('/', {
    templateUrl: '/Reports/Index',
    controller: 'controllerName'
});