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

前端之家收集整理的这篇文章主要介绍了angularjs – 有没有办法将范围传递给指令templateUrl:function?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个指令,我正在循环调用.循环中的每个项都有一个FieldTypeId属性,并且根据FieldTypeId的值,我想换出模板的URL.我觉得这是一种更好的多态方法,而不是在html中执行ng-switch语句.
  1. <div ng-repeat="item in attributes">
  2. <div attribute-input></div>
  3. </div>

当然,此范围内的$scope不可用:

  1. editStudentAccountModule.directive('attributeInput',function () {
  2. return {
  3. restrict: "AE",templateUrl: function () { //
  4. var attribute = $scope.attributes[$scope.$index];
  5. if (attribute.FieldTypeId == 1) {
  6. return '../Templates/dropdown.html';
  7. } else if (attribute.FieldTypeId == 2) {
  8. return '../Templates/radio.html';
  9. } // etc.
  10. }
  11. }
  12. });
您需要在链接函数中加载模板才能访问作用域,然后才能在模板或编译中访问模板本身,请在此处查看: What are the benefits of a directive template function in Angularjs?

如果您实际上直接使用$compile服务,这是显而易见的.当你在某个DOM上调用$compile时,它会返回一个链接函数,然后你调用它来传递一个范围来执行它.因此,当你从那个角度看到它时,很明显在调用编译并返回链接函数然后使用范围调用之前你将不会有范围…它看起来像这样:

  1. $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

在你的代码中,这里有点刺痛:

  1. editStudentAccountModule.directive('attributeInput',scope:{info:"="},link: function(scope){
  2. var templateToUse = '../Templates/default.html';
  3. if (scope.info.FieldTypeId == 1) {
  4. templateToUse '../Templates/dropdown.html';
  5. } else if (scope.info.FieldTypeId == 2) {
  6. templateToUse '../Templates/radio.html';
  7. } // etc.
  8. scope.myTemplate = templateToUse;
  9. },template:"<div ng-include='myTemplate'></div>";
  10. }
  11. });
  12.  
  13.  
  14.  
  15. <div ng-repeat="item in attributes">
  16. <div attribute-input info="item"></div>
  17. </div>

猜你在找的Angularjs相关文章