【问题标题】:How to test the existence of an attribute in a directive?如何测试指令中属性的存在?
【发布时间】:2016-01-05 08:12:02
【问题描述】:

我想根据指令中是否有editable属性来启用一个按钮:

可编辑:

  <table-list items="users" editable></table-list>

不可编辑:

  <table-list items="users"></table-list>

我试过了:

 .directive('tableList', function ($attr) {
    return {
      restrict: 'EA',
      template: '<a ng-if="editable" class="btn btn-default" href="#">Add to group</a>' +
    '<table class="table table-stripped">' +
    '<thead>' +
      '<tr>' +
        '<th>#</th>' +
        '<th>Name</th>' +
        '<th>Users</th>' +
        '<th>Buildings</th>' +
        '<th>Created at</th>' +
      '</tr>' +
    '</thead>' +
    '<tbody>' +
      '<tr ng-repeat="item in items">' +
        '<th scope="row"><input type="checkbox" value="0"></th>' +
        '<td><a href="#/groups/{{item.id}}">{{item.name}}</a></td>' +
        '<td>_</td>' +
        '<td>_</td>' +
        '<td>_</td>' +
      '</tr>' +
    '</tbody>' +
      '</table>',
      scope: {
    items: "=",
    editable: "="
      },

但是按钮没有显示。

这样做的正确方法是什么?

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

如果您只想依赖属性的存在(即使它设置为false),您可以检查它是否使用链接函数中的$attrs 定义:

scope: {
  items: "="
},
link: function($scope, $element, $attrs) {
  $scope.editable = $attrs.editable !== undefined;
}

JSFiddle.

但是,这不会是响应式的(即,如果您在运行时添加属性,指令将不会显示按钮)。如果需要,可以使用$attrs.$observe()

【讨论】:

    【解决方案2】:

    只需添加true:

    <table-list items="users" editable="true"></table-list>
    

    JSFiddle

    【讨论】:

      【解决方案3】:

      当获取属性并将其设置到范围时,就像您设置值一样。而你的 editable-attribute 没有任何价值。如果你愿意 &lt;table-list items="users" editable="true"&gt;&lt;/table-list&gt; 它会更好。

      在指令中,您可能可以使用@ 而不是= 作为属性。

      这会将范围上的可编辑属性设置为字符串“true”,如果您希望它是布尔值,您可能需要在链接函数中添加一些逻辑

      【讨论】:

        猜你喜欢
        • 2017-11-22
        • 1970-01-01
        • 2013-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-13
        • 2019-08-12
        • 1970-01-01
        相关资源
        最近更新 更多