指令中的动态templateUrl

时间:2014-09-05 16:28:46

标签: angularjs angularjs-directive

我有以下指令:

Directives.js

module.directive('vdGuarantees', function () {
    return {
        restrict: 'A',
        template: '<div ng-include="contentUrl"></div>',
        link: function(scope, element, attrs) {
            scope.contentUrl = '../../HTML/Directives/Guarantees/6787.html';
            scope.$watch(scope.clientId, function (newValue, oldValue) {
                console.log(scope.clientId);
                //scope.contentUrl = '../../HTML/Directives/Guarantees/' + newValue + '.html'
            });
        }
    };
});

HTML

<div vd-Guarantees></div>

在我的控制器中,我将$scope.clientId定义为空对象。加载时,控制器正在向Web服务发出$http get请求,并在success上填充$scope.clientId

我想要做的是,当clientId被填充时,相应地更改指令的templateUrl。

1 个答案:

答案 0 :(得分:1)

在我兄弟的帮助下,我得到了解决方案。

第一个错误是我的$watch的定义。应该是:

scope.$watch('clientId', function (newValue, oldValue) {
    //code here
});

我必须改变的第二件事是指令中传递的范围对象。所以我添加了

scope: false
指令定义中的

,使根范围在指令中可用。

完整的指令代码现在看起来像:

module.directive('vdGuarantees', function () {
    return {
        restrict: 'A',
        template: '<div ng-include="contentUrl"></div>',
        scope: false,
        link: function (scope, element, attrs) {
            scope.$watch('clientId', function (newValue, oldValue) {
                if (newValue !== undefined) {
                    scope.contentUrl = '../../HTML/Directives/Guarantees/' + newValue + '.html';
                }
            });
        }
    };
});
相关问题