【问题标题】:how to change the angularjs custom directive templateUrl dynamically with using scope如何使用范围动态更改 angularjs 自定义指令 templateUrl
【发布时间】:2016-06-24 01:04:07
【问题描述】:

这是我的第一个问题,所以我希望我能解释一下情况 angularJs 文档here 讨论了将指令 templateUrl 作为函数动态返回。还有一个 Plunkler 现场演示here

.directive('....', function() {
   return {
     templateUrl: function(elem, attr){
       return **.... scope.Somthing ...**;
     }
   };
 });

该函数没有范围参数,这是主要问题

到目前为止,我发现的唯一方法是动态设置与指令范围相关的 TemplateUrl 是这种方式

.directive('....', function() {
  return {
    link: function (scope, element, attrs) {
      scope.getTemplateUrl = function () {
        return **.... scope.Somthing ...**;
      };
    },
    template: '<ng-include src="getTemplateUrl()"/>'
  };
});

另一种解决方案是

.directive('....', function() {
  return {
    controller: function ($scope) {
      $scope.getTemplateUrl = function () {
        return **.... scope.Somthing ...**;
      };
    },
    template: '<ng-include src="getTemplateUrl()"/>'
  };
});

我的第一个问题是这看起来像是问题的补丁

我的第二个问题是必须在指令中构建 html 字符串。

还有其他方法可以实现吗?

【问题讨论】:

  • 我会在ng-include 中使用变量而不是函数调用,但我认为您所做的一切都很好。如果您对指令中的 HTML 感到不舒服,您可以随时将该 sn-p 保存到文件中。这比注入$compile 并自己动态编译模板要简单得多。

标签: angularjs


【解决方案1】:

让我们把你的问题分成两个问题:D

第一个问题是关于在 js 中存储模板。

这个问题可以使用$templateCache和注入来解决

<script id="myTemplate.html" type="text/ng-template"> <div> SOME MARKUP <div> </script>

Here您可以阅读更多相关信息

第二个问题是关于动态模板。 所以有2个解决方案(据我所知:D) 您已经提到的第一个解决方案 - 使用 ng-include。

第二种解决方案是使用$compile 来动态编译带有角度指令的html。

第一种解决方案稍微好一点,因为在第二种情况下,您必须始终记住内存泄漏。在此处查看更多 infohere

【讨论】:

  • 感谢您的回答,内容非常丰富。所以除了我的问题之外没有其他好的方法吗?..我希望角度团队让模板处理具有范围属性的函数
  • Angular 团队正在使用 Angular 2.0,所以我认为 Angular 1 中的新功能不会很快出现。如果我的回答对你有帮助,请标记为答案。泰。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-09
  • 2013-07-27
  • 2014-05-18
相关资源
最近更新 更多