我可以在两个模板URL之间选择。类似的东西:
angular.factory('SAMPLE',function(){
return {
getnDetails:function($http){
return $http({
method: 'GET',
url: url
});
}
)};
angular.directive() {
controller : function($scope) {
SAMPLE. getnDetails().sucess(){
}.error() {
templateURL: "zbx.html"
}
templateUrl : "xyz.html"
}
这样当我的http请求是一个错误加载完全不同的模板。什么是这样的最佳方式。
答案 0 :(得分:0)
ng-include
可能是你的朋友。部分(希望语法正确)的例子:
angular('app').directive('coolDirective', function () {
return {
scope: {},
controller: function ($scope) {
$scope.template = 'b.html';
if ($scope.condition) {
$scope.template = 'a.html';
}
},
template: '<div ng-include="template"></div>'
}
});
答案 1 :(得分:0)
这是我选择不同模板的方法。关键是templateUrl可以是一个接受元素和属性的函数。
在我的HTML中
<my-directive template="test-template.html"></my-directive>
在我的指令中
.directive('myDirective', function () {
var path = '/app/templates/';
return {
restrict: 'E',
templateUrl: function(tElement, tAttrs) {
return path + tAttrs.template + '.html';
},
controller: function ($scope) {
// whatever...
}
};
})
我喜欢这种方法,因为它允许我对所有逻辑都有一个通用指令,但是从我的HTML控制模板格式来用来显示结果。
根据Angular Directive页面。
注意:您目前无法访问范围变量 来自templateUrl函数,因为之前请求过模板 范围已初始化。
也就是说,您正在努力的解决方案是在出现错误时打开一个完全不同的模板。在这种情况下,您需要使用$location重定向到错误页面,而不是简单地加载不同的模板。或者在主模板中有一个错误处理指令,它会在任何页面上打开错误模式。
希望信息可以帮助您或其他人。