AngularJS组件模板切换

AngularJS组件模板切换,angularjs,Angularjs,我环顾四周,没有找到适合我的答案。我有一个组件,是根据John Papa的风格指南设计的,它可以向用户显示上传的照片 我想实现一些视图,类似于Windows、MacOS如何允许您在详细视图、缩略图和列表视图之间切换 因为视图非常不同,为了使代码处于可维护状态,我希望将这些模板保存在单独的文件中 那么我应该如何实现这一点呢 不同的方法是: .directive('myDirective', function () { return { templateUrl: functi

我环顾四周,没有找到适合我的答案。我有一个组件,是根据John Papa的风格指南设计的,它可以向用户显示上传的照片

我想实现一些视图,类似于Windows、MacOS如何允许您在详细视图、缩略图和列表视图之间切换

因为视图非常不同,为了使代码处于可维护状态,我希望将这些模板保存在单独的文件中

那么我应该如何实现这一点呢

不同的方法是:

.directive('myDirective', function () {
    return {
        templateUrl: function (tElement, tAttrs) {
            if (tAttrs.type) {
                if (tAttrs.type === 'thumb') {
                    return 'thumbnail.html';
                }
                if (tAttrs.type === 'list') {
                    return 'list.html';
                }
                if (tAttrs.type === 'detail') {
                    return 'detail.html';
                }
            }
        }
    }
});
这里的问题是模板很早就决定了,在刷新之前无法更改

 <ng-switch on="post.viewMode">
    <ng-switch when="thumbnail" ng-include="'./thumbnail.html'">
    <ng-switch when="list" ng-include="'/list.html'">
    <ng-switch when="detail" ng-include="'/detail.html'">
</ng-switch>

这似乎是最好的,但ng include创建了一个新的作用域,它抛弃了我的组件结构,所有内容都必须通过作用域访问。$parent.variable


最后一个选项是将所有三个视图放在同一个html模板文件中,如果要使用正确的模板文件,请使用ng。

是的,template/templateUrl函数的方式是错误的,没有作用域或插值属性,这通常被视为控制指令行为的方式

与其他一些内置指令一样,
ng include
是一种快速解决问题的方法(他们称之为“声明性编程”),但也正是由于上述原因,它是一种固执己见的PITA——它强制继承范围,即使您不需要它

.directive('myDirective', function ($templateRequest, $compile) {
    return {
        link: function (scope, element, attrs) {
            var prevTplName;
            var templates = {
                thumb: 'thumbnail.html',
                // ...
            }

            attrs.$observe('type', setTemplate);

            function setTemplate(tplName) {
                if (!templates.hasOwnProperty(tplName) || prevTplName === tplName)
                    return;

                $templateRequest(templates[tplName]).then(function (response) {
                    var contents = $compile(response)(scope);
                    element.empty().append(contents);
                });
            }
        }
    };
});