gpt4 book ai didi

angularjs - 有没有办法将范围传递给指令templateUrl : function?

转载 作者:行者123 更新时间:2023-12-04 03:43:50 24 4
gpt4 key购买 nike

我有一个要在循环中调用的指令。循环中的每个项目都有一个FieldTypeId属性,根据FieldTypeId的值,我想换出模板的URL。我觉得这是一种更好的多态方法,而不是在html中执行ng-switch语句。

<div ng-repeat="item in attributes">
<div attribute-input></div>
</div>

当然,此指令不提供 $scope:
editStudentAccountModule.directive('attributeInput', function () {
return {
restrict: "AE",
templateUrl: function () { //
var attribute = $scope.attributes[$scope.$index];
if (attribute.FieldTypeId == 1) {
return '../Templates/dropdown.html';
} else if (attribute.FieldTypeId == 2) {
return '../Templates/radio.html';
} // etc.
}
}
});

最佳答案

您需要在链接函数中加载模板才能访问范围,然后才可以在模板中或编译时访问模板本身,请在此处 checkout 内容:What are the benefits of a directive template function in Angularjs?

如果您曾经实际直接使用过$ compile服务,则这很明显。当您在某些DOM上调用$ compile时,它会返回链接函数,然后调用该函数传递一个作用域以使其在其上执行。因此,从该 Angular 看时,很明显,只有在调用编译并且返回链接函数然后再使用范围调用之前,您才具有作用域...看起来像这样:

$compile("<div ng-repeat='thing in things'></div>")({things:['thing1','thing2']});//Normally you would pass a scope object in here but it can really be whatever

您的代码有些暗处:
editStudentAccountModule.directive('attributeInput', function () {
return {
restrict: "AE",
scope:{info:"="},
link: function(scope){
var templateToUse = '../Templates/default.html';
if (scope.info.FieldTypeId == 1) {
templateToUse '../Templates/dropdown.html';
} else if (scope.info.FieldTypeId == 2) {
templateToUse '../Templates/radio.html';
} // etc.
scope.myTemplate = templateToUse;
},
template:"<div ng-include='myTemplate'></div>";
}
});



<div ng-repeat="item in attributes">
<div attribute-input info="item"></div>
</div>

关于angularjs - 有没有办法将范围传递给指令templateUrl : function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23987114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com