【问题标题】:Passing an Angular expression to a custom directive将 Angular 表达式传递给自定义指令
【发布时间】:2016-02-24 20:31:27
【问题描述】:

我有这个指令:

    gymApp.directive('ngListar', function() { 
      return { 
        templateUrl: function(elem, attr){
          console.log(attr.type);
          return 'js/directives/listar-'+attr.type+'.html';
        }
      }; 
    });

想法是,当我调用指令时,会添加一个参数,该参数将确定要调用的 html 文件,因此 html 看起来像这样

    <tr ng-listar type="{{list.tipo}}"></tr>

但是日志会打印出 {{list.tipo}} 而不是其中的值。有没有办法可以将表达式作为参数传递?

【问题讨论】:

  • 你试过&lt;tr ng-listar type="list.tipo"&gt;&lt;/tr&gt;吗?也就是说,没有大括号。
  • 没有大括号,控制台日志只会带来:list.tipo 没有大括号。
  • 请避免使用 ng- 作为前缀,因为它是为 AngularJS 内置指令保留的。还要避免使用 type 作为自定义属性,因为浏览器已经使用了该属性名称。
  • 使用ng-include 指令,参见AngularJS ng-include Directive API Reference

标签: angularjs


【解决方案1】:

templateUrl 的文档中描述了这不起作用的原因(强调我的):

由于模板加载是异步的,编译器将暂停 编译该元素上的指令 以供以后使用模板 已经解决了。与此同时,它将继续编译和 链接兄弟元素和父元素,就好像这个元素没有 包含任何指令。

Angular 所做的变量绑定是一个指令,因此在你的指令完成加载其模板之前不会完成。

至于解决方法,您可能需要自己手动调用$compile,而不是依靠templateUrl 来为您做这件事。请参阅$compile 下的第二条注释。

this answer借用一些代码,如果你使用$templateRequest,你可以在你的指令中执行以下操作:

link: function(scope, element, attr){
   $templateRequest('js/directives/listar-' + attr.type + '.html').then(function(html){
      var template = angular.element(html);
      element.append(template);
      $compile(template)(scope);
   });
};

$templateCache$http.get 也应该是与上述代码非常相似的选项。这应该可以解决尚未插入值的问题。

【讨论】:

    【解决方案2】:

    打印你的范围变量,而不是进入 attr。

    app.directive("insertAfter", function(){
        return {
            scope: {
                content: "@",
                type: "@"
            }, 
            link: function(scope, element, attrs){
                console.log(scope.type);
                element.after(scope.content);
            }
        }
      });
    

    【讨论】:

      猜你喜欢
      • 2018-06-14
      • 2015-04-12
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多