【问题标题】:isolate scope on a directive restricted to attributes在仅限于属性的指令上隔离范围
【发布时间】:2015-12-18 19:19:59
【问题描述】:

在指令文档中,您可以使用以下内容隔离范围:

.directive('myDialog', function() {
  return {
    restrict: 'E',
    transclude: true,
    scope: {
      'close': '&onClose'
    },
    templateUrl: 'my-dialog-close.html'
  };
});

我正在尝试编写一个仅限于属性的指令。使用“A”进行限制时,如何获得相同的隔离功能?

.directive('doSomething', function() {
  return {
    restrict: 'A',
    scope: {
      'close': '&???'
    },
    link: function(scope, element, attrs) {
        element.on('click', function() {
            scope.close();
        });
    }
  };
});

我会像这样使用指令:

<button do-something="doSomething()" type="button">Do Something</button>

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    独立作用域不依赖于restrict 属性。您需要提及要从父作用域传递的孤立作用域中的那些变量/方法。

    在下面的隔离范围声明中,您使用close 作为将接受方法的隔离范围变量,这意味着您应该在close 属性中传递该方法实例。

    scope: {
      close: '&' //it shouldn't be with quotes 
    },
    

    标记

    <button do-something close="doSomething()" type="button">Do Something</button>
    

    编辑

    如果你想为你的属性名称设置别名,那么别名将在&amp; 之后出现,如close: '&amp;myAlias',通过使用别名可以避免执行其他指令(理想情况下,你的指令不应该有类似的名称那个)

    scope: {
      close: '&myAlias' //it shouldn't be with quotes 
    },
    

    标记

    <button do-something my-alias="doSomething()" type="button">Do Something</button>
    

    【讨论】:

    • 我是否需要担心其他指令与之冲突?如果我有另一个名为 close 的指令会破坏这个权利?
    • @Dismissile 然后你可以在你的隔离范围声明中使用属性别名..
    • @Dismissile 查看更新后的答案..这将使您清楚地了解如何实现您的要求..
    • 所以如果我希望它是
    猜你喜欢
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多