你可以覆盖AngularUI Bootstrap中的特定模板?

我很好奇,如果有一种方法可以覆盖ui-bootstrap-tpls文件中的单个特定模板。 绝大多数的默认模板符合我的需求,但是有一些特定的模板需要replace,而不需要通过抓取所有默认模板并将它们连接到非tpls版本的整个过程。

是的,来自http://angular-ui.github.io/bootstrap的指令是高度可定制的,并且很容易覆盖其中一个模板(并且仍然依赖于其他指令的默认模板)。;

提供$templateCache就足够了,或者直接提供它(如在ui-bootstrap-tpls文件中所做ui-bootstrap-tpls )或者 – 可能更简单 – 使用<script>指令( doc )覆盖模板。

下面显示了一个人为的示例,其中我将警报的模板更改为将x Close

 <!doctype html> <html ng-app="plunker"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script> <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.4.0.js"></script> <script src="example.js"></script> <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"> <script id="template/alert/alert.html" type="text/ng-template"> <div class='alert' ng-class='type && "alert-" + type'> <button ng-show='closeable' type='button' class='close' ng-click='close()'>Close</button> <div ng-transclude></div> </div> </script> </head> <body> <div ng-controller="AlertDemoCtrl"> <alert ng-repeat="alert in alerts" type="alert.type" close="closeAlert($index)"> {{alert.msg}} </alert> <button class='btn' ng-click="addAlert()">Add Alert</button> </div> </body> </html> 

Live plunker: http ://plnkr.co/edit/gyjVMBxa3fToYTFJtnij?p=preview

使用$provide.decorator

使用$provide来装饰指令可以避免直接使用$templateCache

相反,你可以像平常那样创build你的外部模板html,不pipe你想要什么名字,然后重写指令的templateUrl来指向它。

 angular.module('plunker', ['ui.bootstrap']) .config(['$provide', Decorate]); function Decorate($provide) { $provide.decorator('alertDirective', function($delegate) { var directive = $delegate[0]; directive.templateUrl = "alertOverride.tpl.html"; return $delegate; }); } 

pkozlowski.opensource的plunkr叉: http : //plnkr.co/edit/RE9AvUwEmKmAzem9mfpI ?p=preview

(注意,你必须在指令名称后加上'Directive'后缀,上面我们正在装饰UI Bootstrap的alert指令,所以我们使用alertDirective这个名字。)

正如你可能经常想要做的不仅仅是覆盖templateUrl ,这提供了一个很好的起点,从而进一步扩展指令,例如通过覆盖/包装链接或编译function( 例如 )。

pkozlowski.opensource的答案是非常有用的,并帮助我了很多! 我调整了我的条件,有一个单一的文件定义我所有的angular度模板覆盖,并加载外部JS保持有效载荷的大小。

要做到这一点,去angularui-bootstrap源js文件(例如ui-bootstrap-tpls-0.6.0.jsui-bootstrap-tpls-0.6.0.js并find你感兴趣的模板。复制整个块定义模板和粘贴它进入你的覆盖JS文件。

例如

 angular.module("template/alert/alert.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("template/alert/alert.html", " <div class='alert' ng-class='type && \"alert-\" + type'>\n" + " <button ng-show='closeable' type='button' class='close' ng-click='close()'>Close</button>\n" + " <div ng-transclude></div>\n" + " </div>"); }]); 

然后在ui-bootstrap之后join你的覆盖文件,你就可以得到相同的结果。

Forked版本的pkozlowski.opensource的plunk http://plnkr.co/edit/iF5xw2YTrQ0IAalAYiAg?p=preview

您可以使用template-url="/app/.../_something.template.html"覆盖该指令的当前模板。

(至less在手风琴引导中工作)