我正在尝试使用此Keyword
中的提示动态设置指令的模板这是我的指令的代码。
var app = angular.module('sck-table', [
]).directive('tableInput', function(){
return {
restrict: 'E',
scope: {
field:'=field',
},
template:'<ng-include src="getTemplateUrl()"/>',
controller: function($scope){
$scope.count = 0;
$scope.getTemplateUrl = function() {
$scope.count++;
console.log('this has been ran: '+$scope.count);
console.log($scope.field.type);
if($scope.field.type === 'select'){
return 'table/views/table-input-select.html';
}
if($scope.field.type === 'number'){
return 'table/views/table-input-number.html';
}
};
}
};
});
我在运行2次的ng-repeat指令中使用此指令。(test.fields的长度为2)
<td ng-repeat="field in test.fields">
<table-input field="field" ></table-input>
</td>
我希望函数getTemplateUrl()能够运行两次。对于test.fields中的每个项目一次。
但是,当我运行此操作时......控制台会记录28次。link
我似乎得到了理想的结果...意味着模板已成功注入页面,但我想知道是否有人能告诉我为什么getTemplateUrl()函数被调用了很多次,如果我可以做任何事情为了防止这种情况。
提前致谢。
答案 0 :(得分:0)
感谢我的问题及相关帖子留下的评论,我提出了这个解决方案。
var app = angular.module('sck-table', [
]).directive('tableInput', function(){
var contentUrl;
return {
restrict: 'E',
scope: {
field:'=field',
},
link: function(scope,element,attrs){
scope.contentUrl = 'table/views/table-input-'+scope.field.type+'.html';
},
template: '<ng-include src="contentUrl"/>'
};
});