2015-02-19 22 views
11

Uygulamamda angularjs kullanıyorum, her şey iyi çalışıyor, ancak şablonu yüklemeden önce, yalnızca belirli bir yol üzerinde var olduğunu kontrol etmek istiyorum.angularjs yolları, şablon dosyasının var olup olmadığını kontrol etme

.when("/:page", angularAMD.route({ 

     templateUrl: function (rp) { 
        return 'public/templates/' + rp.page.replace('.html', '') + '.php'; }, 

     resolve: { 
     load: ['$q', '$rootScope', '$location', 
      function ($q, $rootScope, $location) { 

       var path = $location.path(); 
       //console.log(path); 
       var parsePath = path.split("/"); 

       var controllerName = parsePath[1]; 
       controllerName = controllerName.replace('.html', '').replace('_', ''); 
       var loadController = "public/js/controllers/" + 
             controllerName + "Controller.js"; 

       var deferred = $q.defer(); 
       require([loadController], function() { 
         $rootScope.$apply(function() { 
         deferred.resolve(); 
       }); 
      }); 
      return deferred.promise; 
      }] 
     } 

    })) 

Bu dosya varsa bu return 'public/templates/' + rp.page.replace('.html', '') + '.php'; } yapmadan önce o kontrol gerektiğini istemek, aksi halde 404 sayfaya yönlendirme istiyorum:

İşte benim kodudur.

şimdi ne oluyor, geçersiz bir bağlantıyı ziyaret ettiğimde, 404 durumunu alamıyorum, bunun yerine ana index.html dosyasını yükler ve bu nedenle, aynı kodu sonsuz bir döngüde sonda çalıştırmaya başlar. tarayıcı kilitleniyor.

Yardımlarınız için teşekkür ederiz, teşekkürler.

+0

neden kullanmayan $ routeChangeError veya NOTFOUND size kullanıcıyı yönlendirmek için düşüncelerini daha verimli şekilde uygulanması (bir şey) olay başka sayfa – micronyks

+0

bana bir örnek verebilir misiniz, $ routeChangeError nasıl kullanılır? Bu, –

+0

http://stackoverflow.com/questions/20894568/display-specific-template-on-routechangeerror checkout. – micronyks

cevap

0
(or $scope.$on) 
$rootScope.$on("$routeChangeError", function(event, current, previous, eventObj) { 
    //redirect your user to custom 404 page; 
    }); 
+0

ama bu kodu nereye yerleştirdim? yükte: ['$ q', '$ rootScope', '$ location', 'bölüm? Zaten burada denedim, çalışmadım, sebebi, URL geçersiz olsa bile asla hata alamam. –

0

Eğer mainmodule ardından bir yapılandırma blok ve ardından koşmak bloğu tanımlamak nerede muhtemelen kendileri için en iyi yer doğru, sadece önemsiz olmayan herhangi angularjs uygulamasında yapmanız gereken birkaç şey vardır. İşte taşıma ve bu $ routeChange Olaylar günlüğü olmadan

(sırasıyla. Ui-yönlendirici $ stateChange Olaylar kullanılırken) temelde kör ve hataları kaçırmak ve rota değişiklikleri ve diğer kötü şeyler çoğaltmak olacak ...

örnek ui yönlendiriciyi kullanırken, açısal temel yönlendirme kullanıyorsanız, açısal yönlendiricinin tekrarlanan olaylarını kullanın.

angular.module('yourMainModuleName', ['your dependencies']) 

.config(['$someProvider', function(someProvider) { 
    // do setup all your global providers here 
    // e.g. $http, restangular, ui-router, angular-translate.... 

} ]) 

.run(['$rootScope', '$state', '$stateParams', 
function($rootScope, $state, $stateParams) { 

    // put ui-router $state on $rootScope, so we have access to it in all $scopes 
    $rootScope.$state = $state; 
    $rootScope.$stateParams = $stateParams; 

     $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) { 
      // always see what happens in your app! 
      console.debug('stateChangeStart from: ' + (fromState && fromState.name) + ' to: ' + toState.name); 
      // handle auth here as well, check whether user is allowed to go to this state, abort if not 
      ... 
     }); 

     $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) { 
      // see what happens in your app! 
      console.debug('stateChangeSuccess from: ' + (fromState && fromState.name) + ' to: ' + toState.name); 
     }); 

     // log stateChangeErrors 
     $rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) { 
      console.log('Error on StateChange from: "' + (fromState && fromState.name) + '" to: "'+ toState.name + '", err:' + error.message + ", code: " + error.status); 
      $state.go('home'); 
     }); 

}]); 
+1

Bu şeyi anlıyorum, ama benim sorunum benim betiğimde hata döndürmüyor, işte bir örnek, bu URL'yi çalıştırdığımı varsayalım 'mydomain.com/hello.html', komut dosyası bu yoldan şablon dosyasını döndürecek 'public/templates/hello.html' ancak bu hello.html aslında mevcut değil, bu yüzden bu dosyayı yüklemek veya hata vermek yerine, angularjs libs ve bcoz içerdiği ana uygulama dosyası olan index.html dosyasını yükler. index.html dahil olmak üzere, döngüdeki angularjs libs'i yükler, bu nedenle ajax tonlarının tonları ve son tarayıcı çökmesiyle, umarım durumumu açıklayabiliyorum. –

0

Dosyanın olup olmadığını kontrol eden bir hizmet oluşturun ve bir söz verir! denetleyici olarak

$http.head("template2check").then(function() { 
       return true; 
      }, function() { 
       return false; 
      }); 

servisini kullanmak:

<service>.<service method>.then(function (found) { 
    if (found) {...... 
}); 
1

ngRoute olarak, config blokta yolları yapılandırmak gerekir ve yapılandırma bloğunun içinde size fabrikaları ve hizmetlerini
kullanamaması için Şablonun mevcut olup olmadığını ve 404 sayfanızı iade etmediğinizi kontrol etmek için basit bir numara kullanabilirsiniz.

var checkTplUrl = function(url) { 
    var http = new XMLHttpRequest(); 
    http.open('HEAD', url, false); 
    http.send(); 
    return (http.status !== 404) ? url : './404.html'; 
}; 


.when("/:page", angularAMD.route({ 

    templateUrl: function (rp) { 
     return checkTplUrl('public/templates/' + rp.page.replace('.html', '') + '.php'); }, 

    resolve: { 
     load: ['$q', '$rootScope', '$location', 
      function ($q, $rootScope, $location) { 

       var path = $location.path(); 
       //console.log(path); 
       var parsePath = path.split("/"); 

       var controllerName = parsePath[1]; 
       controllerName = controllerName.replace('.html', '').replace('_', ''); 
       var loadController = "public/js/controllers/" + 
         controllerName + "Controller.js"; 

       var deferred = $q.defer(); 
       require([loadController], function() { 
        $rootScope.$apply(function() { 
         deferred.resolve(); 
        }); 
       }); 
       return deferred.promise; 
      }] 
    } 

})) 

Çalışma örneği: Sonra https://plnkr.co/edit/1UjlFgT7dazMZOrAhZzY?p=info

İlgili konular