所以基本上我有一个网页“索引”,其中有一个表单和一个 ng-view 部分。
所以我想要的是用户填写表单中的一些字段并提交它,ng-view 将在表单下方呈现服务器行程的结果。
而且它有效!当此 View 加载时,它会使用从表单中填写的值访问服务器,返回数据并将其呈现到页面。
我遇到的问题是这只有效一次。
填写表格,点击提交,结果页面将加载在其下方。 更改表单中的值并再次提交,它不会将查询触发回服务器。
谁能告诉我哪里出错了?
这是我的第一个 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);
};
});
我假设这是因为在初始化 Controller 时加载了数据。而且它仅在页面首次加载时初始化,而不是在后续提交时初始化。
最佳答案
您的 View 未重新加载的原因是 $location 进行了一些优化。如果路径不更改,则不会重新加载页面。解决这个问题的方法是使用
$route.reload();
但是您的代码还可以使用更多的组织...与其将服务器请求绑定(bind)到加载 Controller ,为什么不将服务器请求代码移至您的搜索功能呢?更好的是,您可以创建一个服务来处理可在每个 Controller 中重复使用的 HTTP 请求。了解有关 Angular 服务的更多信息 here .
关于你的第二个问题:当你取消注释该行时,你的浏览器会崩溃,因为你传递给 $routeProvider 的路由对象需要一个 Controller 。
您的路线应如下所示,但将“controllerName”替换为您的实际 Controller 。
$routeProvider.when('/', {
templateUrl: '/Reports/Index',
controller: 'controllerName'
});
关于javascript - 表单 ng-submit 加载 subview ,但仅加载一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39019031/