我有一个循环调用的指令。循环中的每个项目都有一个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.
}
}
});
您需要在链接函数中加载模板才能访问范围,然后才可以在模板中或通过编译访问模板本身,请在此处查看以下内容:指令的好处是什么Angularjs中的模板函数?
如果您曾经实际直接使用过$ compile服务,则这很明显。当您在某个DOM上调用$ compile时,它会返回链接函数,然后调用该函数传递一个作用域以使其在其上执行。因此,从该角度看时,很明显,只有在调用编译并且返回链接函数然后再使用范围调用之前,才具有作用域...看起来像这样:
$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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句