【问题标题】:Angular directives - How to select template based on attribute values?Angular 指令 - 如何根据属性值选择模板?
【发布时间】:2014-05-02 09:17:04
【问题描述】:

我正在开发一个小部件,我想在其中一个接一个地呈现一些消息/文本。我想根据消息的类型更改消息的模板。

我目前的指令设置如下

directive('cusMsgText', function(){
  return {
     restrict: 'E',
     template:function(elements, attrs){
        return '<div></div>';
     },
     link: function($scope, iElm, iAttrs, controller) {
        //add children to iElm based on msg values in $scope
     }
  };
});

指令使用如下

<div ng-repeat="(key, value) in chatUser.msg">  
    <data-cus-msg-text msg="value.type"></data-cus-msg-text>  
</div>

现在我的问题是-:

  1. 是否可以从以下位置返回多个字符串(模板)之一 模板函数本身基于属性的实际值 msg。我尝试在模板函数中访问attrs.msg,它 返回value.type

  2. 如果不是那么,在linker下操作模板好还是我 需要将其移至compile 函数吗?

【问题讨论】:

    标签: javascript angularjs templates angularjs-directive


    【解决方案1】:

    要基于value.type 呈现不同的模板,您可以使用ng-switch 语句:

    <div ng-switch="value.type">
        <div ng-switch-when="type1">
            //...template for type 1 here...
        </div>
        <div ng-switch-when="type2">
            //...template for type 2 here...
        </div>
    </div>
    

    另外,如果我理解你的第二个问题:未编译指令的操作应该在compile 函数中完成,编译后发生的所有操作都应该在link 函数中进行。

    Docs for ngSwitch

    编辑:向 Sebastian +1 了解您想要什么。然而,他的提议本质上是重新发明轮子,因为它本质上是手动编译和插入模板(这就是 ngSwitch 为您所做的)。此外,您可以通过 link 函数的 attrs 参数访问您放在指令中的属性。

    【讨论】:

    • 我无法访问指令属性中提供的实际值。模板函数下的 value.type 是一个字符串。
    • 在您提供的示例中,您的指令具有msg 属性。如果我理解,您可以通过该属性将类型传递给指令。你可以在那个值上switch,我看不出问题。此外,“模板功能”是什么意思? Link函数?
    【解决方案2】:

    template 函数中,您无权访问指令的scope。如果您想控制渲染的内容,您可以按照 simoned 的建议在全局模板中使用条件逻辑(例如 ng-switch)或使用 link 函数:

    .directive('cusMsgText', function($compile) {
      return {
        restrict: 'E',
        scope: {
          msg: '=',
          item: '='
        },
        link: function(scope, element, attrs) {
          templates = {
            x: '<div>template x {{item.name}}</div>',
            y: '<div>template y {{item.name}}</div>'
          };
    
          var html = templates[scope.msg];
          element.replaceWith($compile(html)(scope));
        }
      };
    });
    

    【讨论】:

    • 不能解析模板函数中的属性值吗? +1。
    猜你喜欢
    • 1970-01-01
    • 2019-03-21
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多