【问题标题】:angularjs component with dynamic templateUrl带有动态templateUrl的angularjs组件
【发布时间】:2017-08-10 15:03:14
【问题描述】:

是否可以使用动态 templateUrl 创建 AngularJS 组件? 意味着我想将服务注入到为我提供模板基本路径的组件中:

即:templateUrl: configuration.baseScriptPath + '...html'

使用 Directive 是可能的,但是如何使用 Component 做到这一点?

angular.module('runtime')
    .component('textInput', {

        templateUrl: /*configuration.baseScriptPath + */'fd/components/text_input_instance.html',
        controller: [
            '$scope', '$element', 'focusInputGroup', 'configuration',
            function ($scope, $element, focusInputGroup, configuration) {

【问题讨论】:

  • 如果它在指令中工作,它也应该在组件中工作,因为'templateUrl'属性没有被修改..
  • 我想注入配置,以便在 templateUrl 中可用。
  • 你能分享你的组件代码吗?
  • 刚刚添加。评论显示了我想要完成的事情,但是如何注入配置?

标签: javascript angularjs


【解决方案1】:

你可以使用template和ng-include代替templateUrl,像这样:

angular.module('runtime')
    .component('textInput', {

        template: '<div ng-include="getTemplate()">',
        controller: [
            '$scope', '$element', 'focusInputGroup', 'configuration',
            function ($scope, $element, focusInputGroup, configuration) {

           $scope.getTemplate = function () {
               return configuration.baseScriptPath + 'fd/components/text_input_instance.html';
          };

【讨论】:

    【解决方案2】:

    组件的templateUrl 属性也带有一个函数。所以你可以试试这个,

    angular.module('runtime')
      .component('textInput', {
    
          templateUrl: ['$configuration', function($configuration) {
            return $configuration.basepath + '.html'
          }],
          controller: [
              '$scope', '$element', 'focusInputGroup', 'configuration',
              function($scope, $element, focusInputGroup, configuration) {
    

    【讨论】:

    • 应该是templateUrl: [...],否则只会打印HTML模板文件名,因为template是一个字符串。
    • 正确。我习惯使用 .
    猜你喜欢
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 2017-02-01
    • 2018-01-31
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多