2016-08-18 103 views
0

所以基本上我有一個網頁'索引',它有一個窗體和一個ng-view部分。
所以我想要的是用戶填寫表單中的一些字段並提交它,ng-view在服務器旅程的結果下呈現在表單下。表格ng-submit加載一個子視圖,但只有一次

它的工作原理!當這個視圖加載時,它會使用從表單填寫的值擊中服務器,並返回數據並將其呈現給頁面。

我的問題是,這隻能工作一次。

填寫表單,點擊提交,結果頁面加載到它下面。 更改表單中的值並重新提交,並且不會將查詢發回服務器。

誰能告訴我我哪裏出錯了嗎?
這是我的第一個角度應用程序,我一直在尋找事物 - 所以我甚至不確定這是做事的可接受方式。

紅利問題:誰能告訴我爲什麼當*//$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); 
    }; 
}); 

我假定這是因爲當控制器初始化加載數據。它只在頁面第一次加載時才被初始化,而不是在後續的提交中。

+0

嘗試$ routeProvider.when('/','/ Reports/Index'); – Damiano

回答

1

您的視圖未重新加載的原因是由於$ location所做的某些優化。如果路徑沒有改變,頁面將不會被重新加載。要解決這個問題的方法是使用

$route.reload(); 

但是你的代碼也可以使用一些更多的組織......而不是綁在服務器請求加載器,爲什麼不把服務器請求代碼移到搜索功能?更好的是,您可以創建一個服務來處理可在每個控制器中重複使用的HTTP請求。閱讀更多關於角度服務here

關於第二個問題:當您取消註釋該行時,您的瀏覽器崩潰,因爲您傳遞給$ routeProvider的路由對象需要控制器。

您的路線應該如下,但用您的實際控制器替換'controllerName'。

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