定义Angular模板的更简洁的方式

Cleaner way for defining Angular templates

本文关键字:方式 简洁 Angular 定义      更新时间:2023-09-26

考虑以下代码

my_app.run( [ '$templateCache' , function( $templateCache ) {
    var template = "" +
        "{{ item.name }}" +
        "<ul ng-if='item.sub'>" +
            "<li ng-repeat='item in item.sub' ng-include='"'angular-multi-select-item.htm''"></li>" +
        "</ul>" +
        "";
    $templateCache.put( 'angular-multi-select-item.htm' , template );
}]);

虽然这工作如预期,我认为它相当丑陋(与html内部连接字符串)。有没有其他更干净的方式来定义Angular模板的html ?

你怎么看?在你的工作目录下创建一个viewhtml视图文件,并使用$http加载。

$templateCache.put('angular-multi-select-item.htm', $http.get('views/template.html'));

您也可以尝试使用' ng-include?(文档)并在主视图中添加include,如:

<div ng-include="'views/template.html'"></div>