angularjs如何动态更改临时url

angularjs how to change tempate url dynamically

本文关键字:url 动态 何动态 angularjs      更新时间:2024-05-18

我的模块中有一个指令。我想根据一个属性更改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

解决方案1:

scope.$watch('stage', function(condition){
    var templateUrl;
    if(stage === 'welcome'){
        templateUrl = "hello.html";
    } else{
        templateUrl = "someothertemplate.html";
    };
    //load the template;
    $http.get(templateUrl)
        .then(function (response) {
            // template is loaded.
            // add it and compile it.
            angular.element(element).html(response.data);
            $compile(element.contents())(scope);
        });
});

解决方案2:使用ng包括

<div test stage="dynamicstage">
    <div ng-include="templateUrl"></div>
</div>

内部指令:

scope.$watch('stage', function(condition){
    var templateUrl;
    if(stage === 'welcome'){
        templateUrl = "hello.html";
    } else{
        templateUrl = "someothertemplate.html";
    };
    scope.$parent.templateUrl = templateUrl; // make sure that templateUrl is updated in proper scope
})