在Angular中,视图可以在代码中加载吗?

In Angular, can view be loaded in code?

非常简单,在 API 调用之后,根据 return 值,如何加载适当的视图?考虑拥有

search.html
views/found.html
views/notfound.html

Search 的控制器对服务进行 AJAX 调用并获得好的或坏的结果。现在我想要加载适当的视图,而无需用户单击。我只是想不出如何做到这一点,并查看了数十个 routing/view 示例。我正在使用 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;
        });

收到有关如何在模板中调用视图的回复后,我迷路了。

由于您使用的是 ngRoute,因此请使用 $location.path() 而不是 $state.go()$location.path() 方法接受路由配置中指定的 url。例如:

$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');
            });
   });    

参考 https://docs.angularjs.org/api/ng/service/$location 获取 $location.path

的 api 文档