Ada*_*itt 9 angularjs angularjs-directive angularjs-scope
我有一个指令,我正在循环调用.循环中的每个项都有一个FieldTypeId属性,并且根据FieldTypeId的值,我想换出模板的URL.我觉得这是一种更好的多态方法,而不是在html中执行ng-switch语句.
<div ng-repeat="item in attributes">
<div attribute-input></div>
</div>
Run Code Online (Sandbox Code Playgroud)
当然,$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.
}
}
});
Run Code Online (Sandbox Code Playgroud)
sha*_*ain 11
您需要在链接函数中加载模板才能访问范围,在此之前您只需在模板或编译中访问模板本身,请查看此处的说明:指令的好处是什么? 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
Run Code Online (Sandbox Code Playgroud)
在你的代码中,黑暗中有点刺伤:
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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9784 次 |
最近记录: |