【问题标题】:AngularJS: replacing templateURL with 404 page url when data is not loadedAngularJS:在未加载数据时将 templateURL 替换为 404 页面 url
【发布时间】:2015-01-20 06:11:56
【问题描述】:

这当然行不通,但应该解释我想要实现的目标:

在工厂 "myapp.factory('gameService', function($http, $location) {" 我从 json feed 加载数据 "return $http.jsonp('api/game/' + id + '?callback=JSON_CALLBACK')",如果没有加载数据,将最初加载的templateURL改为404页面url。

var get_data = function (id) {
     return $http.jsonp('api/game/' + id + '?callback=JSON_CALLBACK')
            .then(function(response) {
               //data loaded, do magic
            }, function(response) {
                //data not loaded
                templateUrl: 'views/page_not_found.html'; //<- how to inject this so it works?
            });
};

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    最好的方法是在路由提供者中设置一个状态为“找不到页面”,如下所示:

    app.config(function ($routeProvider) {
        $routeProvider
          .when('/', {
            templateUrl: 'views/main.html'
            controller: 'MainCtrl',
          })
          .when('/pageNotFound', {
            templateUrl: 'views/page_not_found.html'
          });
    });
    

    在你的函数中做这个:

    var get_data = function (id) {
        return $http.jsonp('api/game/' + id + '?callback=JSON_CALLBACK')
            .then(function(response) {
               //data loaded, do magic
            }, function(response) {
                //data not loaded
                window.location = '/#/pageNotFound';
            });
    

    };

    【讨论】:

    • 这只会创建无限循环。
    • 无限循环?你试试看?
    【解决方案2】:

    用 ng-switch 和 ng-include 修复它

    在控制器中,未加载数据时我添加了:

    $scope.page_not_found = true;
    

    在我添加的模板中:

    <div ng-switch on="page_not_found">
       <div ng-if="page_not_found" ng-include="'views/page_not_found.html'"></div>
    </div>
    

    它并没有真正取代 templateURL,一切都发生在一个 .html 模板中。我隐藏了主要内容并用ng-include导入404页面,这个解决方案似乎也更快。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-29
      • 2017-08-18
      • 2018-12-04
      • 1970-01-01
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多