我有一个指令,我正在循环调用.循环中的每个项都有一个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. } } });
您需要在链接函数中加载模板才能访问作用域,然后才能在模板或编译中访问模板本身,请在此处查看:
What are the benefits of a directive template function in Angularjs?
原文链接:https://www.f2er.com/angularjs/141306.html如果您实际上直接使用$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',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>