我有类似的需求,但发现内置$templateCache
和 ui.router 的$templateFactory
行为不一致。当我用这个...
$templateFactory.fromUrl( './non-existant.html' )
.catch( function( err ){ console.log( 'does not exist' )})
...它将无法触发 catch 回调。只有在两次点击此调用后才会触发错误。
$q
所以我使用and推出了自己的解决方案XMLHttpRequest
:
.service( 'templateUtils', [
'$q'
function( $q ){
var api = {
hasTemplate: function( url ){
var d = $q.defer()
var rqst = new XMLHttpRequest()
rqst.open( 'GET', url )
rqst.onload = function( evt ){
if( evt.target.status === 200 )
d.resolve( true )
else
d.reject( false )
}
return d.promise
}
}
return api
}
])
我是这样用的...
var templateUrl = './default-template.html'
templateUtils.hasTemplate( urlToCheck )
.then( function( rsp ){ templateUrl = './different-template.html' })