1

我可以在两个模板URL之间有一个选项。像这样:单个指令中的可选/多个模板URL Angular JS

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

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>' 
    } 
}); 
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重定向到错误页面,而不是简单地加载其他模板。或者也许在主模板中有一个错误处理指令,它会在任何页面上打开一个错误模式。

希望信息可以帮助你或其他人。