【问题标题】:Is there a way to know the name of the model used in a directive?有没有办法知道指令中使用的模型的名称?
【发布时间】:2023-03-19 20:37:01
【问题描述】:

假设我有以下指令:

.directive("counter", function () {
            return {
                restrict: "E",
                scope:{
                    bindModel:'=ngModel'
                },
                templateUrl: "/directives/countertemplate.html"

和模板:

<div id="counter" ng-class="{true: 'twitter-counter'}[bindModel.length > 140]">
  {{140 - bindModel.length}}
</div>

有没有办法让我知道传递给指令的模型名称:

 <counter ng-model="twitterPost"></counter>

例如,我想从模板的上下文中知道“twitterPost”被发送到模板,所以我可以执行与“facebookPost”不同的逻辑集

【问题讨论】:

  • 使用不同的属性

标签: angularjs angularjs-directive angularjs-scope directive angular-ngmodel


【解决方案1】:

您应该以有角度的方式进行,传递包含您需要的所有信息的对象并处理指令中的逻辑,例如 在这个小提琴中: //jsfiddle.net/HB7LU/6052/

【讨论】:

    【解决方案2】:

    在链接功能中,您可以从元素中检索所有属性。 DEMO

    template: "<div ng-show='isTwitterPost'>Twitter</div><div ng-show='!isTwitterPost'>Facebook</div>",
    link: function ($scope, element, attrs) {
      $scope.isTwitterPost = attrs.ngModel === 'twitterPost';
    }
    

    你应该添加额外的属性。

     <counter ng-model="twitterPost" is-twitter='true'></counter>
    

    【讨论】:

      猜你喜欢
      • 2011-09-29
      • 2011-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      相关资源
      最近更新 更多