【问题标题】:Using external Javascript files inside an Angular directive template在 Angular 指令模板中使用外部 Javascript 文件
【发布时间】:2014-07-16 17:27:35
【问题描述】:

我在我的 webapp“组件”中动态加载,它有一个指令和一个模板,如下所示:

angular.module('app')
.directive('carousel', function() {
return {
  restrict: 'E',
  scope: {
  left: '@',
  top: '@'
  },
  templateUrl: 'carousel.html'
};

});

此模板可以具有 CSS 依赖项,并且可以使用,但不适用于 Javascript。你认为它会如何运作?

模板示例 (carousel.html)

<link rel="stylesheet" type="text/css" href="example.css" media="all"> //This works
<script src="jquery.min.js"></script> //This don't work. It doesn't even request the  file to the server.
<script>
  alert('This alert is not executed');
  function alertFn(){
    alert('This alert is not executed even calling the function from other parts of the code');
  }
</script>
<p class="templateExample">This template paragraph is loaded correctly in the view</p>

【问题讨论】:

  • 如果这是用于 jQuery 的,只需将其加载到主模板中并将其列为依赖项。很可能其他指令也会使用它,然后您最终会多次包含它。
  • 我希望它是用于 jQuery,但是这个组件可以有任何类型的依赖,所以当用户将组件导入应用程序时,我可以看到 2 个选项: - 一些管理依赖关系的文件,并重新加载然后页面。 - 一些“角度”的方式来做到这一点。
  • 如果它是一个依赖项,我认为我仍然会将它包含在主模板中。我假设它是某种图书馆。如果它不是库,而是组件特定的东西,那么它应该被添加到组件中。但这只是我的 2c。
  • 谢谢,我正在尝试将它包含在模板中,但它不起作用。而且我不能预先将它包含在应用程序中,因为正在运行的应用程序应用程序中上传了新的“组件”,这个“组件”确实包含指令、模板等,所以你无法提前知道你的依赖项有。

标签: javascript html angularjs angularjs-directive


【解决方案1】:

最后使用jquery作为主要依赖解决了这个问题。

根据经验,我可以看到,当您使用 Javascript 文件时,模板中的脚本会被有效加载。

【讨论】:

    猜你喜欢
    • 2015-05-05
    • 1970-01-01
    • 2014-03-24
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多