很简单,在API调用之后,根据返回值,如何加载适当的视图?考虑拥有
search.html
views/found.html
views/notfound.html
搜索的控制器对服务进行AJAX调用并获得好的或坏的结果。现在我希望加载适当的视图,而无需用户点击。我只是无法弄清楚如何做到这一点,并看了几十个路由/视图示例。我正在使用HTML5模式。
app.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'search.html',
controller: 'searchCtrl'
})
.when('found', {
templateUrl: 'views/found.html',
controller: 'foundCtrl'
})
.when('notFound', {
templateUrl: 'views/notFound.html',
controller: 'notFoundCtrl'
})
.otherwise({
templateUrl: 'search.html',
controller: 'searchCtrl'
});
$locationProvider.html5Mode({
enabled: true,
requiredBase: true
});
在控制器中..
$scope.post = function (requestType, requestData) {
var uri = 'Search/' + requestType;
$http.post(uri, requestData)
.success(function (response) {
$scope.searchResult.ID = response.ID;
$scope.searchResult.Value = response.Value;
// how is the view/route loaded without a user click?
'found';
return true;
}).error(function (error) {
// how is the view/route loaded without a user click?
'notFound';
return false;
});
在收到关于如何在模板中调用视图的响应之后,我才迷失了。
答案 0 :(得分:1)
由于您使用ngRoute
使用$location.path()
而不是$state.go()
。 $location.path()
方法接受路由配置中指定的URL。 E.g:
$location.path('/found');
假设你的控制器是AppController
,那么完整的代码将类似于:
angular.module('app', ['ngRoute'])
.controller('AppController', function ($location, $http) {
$scope.post = function (requestType, requestData) {
var uri = 'Search/' + requestType;
$http.post(uri, requestData)
.success(function (response) {
$scope.searchResult.ID = response.ID;
$scope.searchResult.Value = response.Value;
// how is the view/route loaded without a user click?
$location.path('/found');
}).error(function (error) {
// how is the view/route loaded without a user click?
$location.path('/notFound');
});
});
有关$location.path