javascript - 无法将 attrs.value 移交给 Directive 的 templateUrl 函数

标签 javascript angularjs

使用 Angular 1.6,我定义一个指令,如下所示:

angular
    .module('myApp')
    .directive('lyEntity', lyEntity);

function lyEntity() {
    return {
        restrict: 'E',
        scope: {
            model: '=',
            type: '@'
        },
        controller: 'lyEntityController',
        controllerAs: 'vm',
        bindToController: true,
        templateUrl: function (elem, attrs) {
            return 'components/_templates/' + attrs.type + '.html'
        }
    };
}

但是在另一个模板中使用它,如下所示:

<ly-entity model="vm.entity" type="{{vm.type}}"></ly-entity>

将生成 templateURL components/_templates/{{vm.type}}.html

如何将 vm.type 的值移交给我的 templateUrl 函数?

最佳答案

是的,它不能按照您尝试的方式完成,因为在插入属性之前调用 templateUrl 函数。实现此目的的一种方法是使用 ng-include

return {
    restrict: 'E',
    scope: {
        type: '@'
    },
    link: function(scope, element, attrs){
        $scope.templateUrl = 'components/_templates/' + attrs.type + '.html';
    },
    template: '<ng-include src="templateUrl"/>'
};

因此,在 Controller 中构造模板url,以ng-include作为模板,并将src指向构造的模板url。

这是一篇关于如何拥有动态模板的好文章:https://medium.com/angularjs-meetup-south-london/angular-directives-using-a-dynamic-template-c3fb16d03c6d#.mizywdk6s

关于javascript - 无法将 attrs.value 移交给 Directive 的 templateUrl 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42595026/

相关文章:

javascript - 使用 foreach 和 switch 循环遍历数组并在 angularjs 中返回不同的值

javascript - 如何将 "tick"按钮放入 jquerymobile 滑动面板

javascript - 如何在不破坏 Angular 模型(数组)的情况下过滤它

javascript - 如何在 React Native 中运行后台任务?

javascript - 在 JavaScript 函数中添加时间延迟以实现淡入淡出效果

javascript - 如何从评级系统获取值(value)并保存到数据库

javascript - 删除并破坏 angularjs 中特定位置的 json 数据

javascript - 使用 AngularJS 自定义可过滤下拉菜单

AngularJS 中工厂内的 JavaScript 作用域

javascript - 在 JavaScript 中实现 Lisp 的缺点