javascript - angularjs如何动态更改模板url

标签 javascript angularjs angularjs-directive

我的模块中有一个指令。我想根据属性更改 templateUrl

HTML

    <div test stage="dynamicstage"></div>

模块

angular.module('trial', [])
    .controller('trialCtrl', function ($scope) {
        $scope.dynamicstage = 'Welcome';
    })
    .directive('test', function () {
    return {
        restrict: 'A',
        scope: {
            'stage': '='
        },
        link: function (scope, element, attrs) {
            scope.$watch('stage', function(condition){
                if(stage === 'welcome'){
                   templateUrl: "hello.html";
                }else{
                    different template url...
                };
            });
        }
    }
});

这是行不通的。 templateurl 未加载到 div 中。我想动态更改 templateUrl 这可能吗?

感谢任何帮助。

最佳答案

这在 Angular 中不是很透明。 templateUrl 可以是动态构建模板 URL 的函数,但是在您的情况下,您需要一个范围,在构建 URL 时尚不可用。

你可以在 ngInclude 的帮助下做这样的事情:

app.directive('test', function() {
    return {
        restrict: 'A',
        scope: {
            'stage': '='
        },
        template: '<div ng-include="templateUrl"></div>',
        link: function(scope, element, attrs) {
            scope.$watch('stage', function(condition) {
                if (scope.stage === 'Welcome') {
                    scope.templateUrl = "hello.html";
                } else {
                    scope.templateUrl = "other.html";
                };
            });
        }
    }
});

演示: http://plnkr.co/edit/l1IysXubJvMPTIphqPvn?p=preview

关于javascript - angularjs如何动态更改模板url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28717328/

相关文章:

javascript - 将 JavaScript 中的 HTTP header 添加到图像请求中

javascript - 使用动态配置选项动态加载 highcharts

javascript - 如何在 Angular 中制作自定义指令以使用谷歌地图计算距离

angularjs - Nativescript 找不到模块 'nativescript-angular/http'

javascript - API 完成后初始化指令

javascript - Nodejs 中 undefined variable 无法显示错误

javascript - 使用 jQuery 从 html 元素传入参数

javascript - 如何使用 JavaScript 禁用 TextBox?

angularjs - ng-repeat 输入复选框中的 Ng-model 属性始终为文字或给出错误

javascript - 在 AngularJS 中准备多选列表时如何选择多个选项