2014-09-05 93 views
0

我有以下指令:动态templateUrl在指令

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作为一个空对象。在加载时,控制器正在向网络服务请求$http,并在success上填充$scope.clientId

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

回答

0

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

第一个错误是我的$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'; 
       } 
      }); 
     } 
    }; 
});