指令中的两种数据绑定,而无需隔离范围



我有一个指令,该指令需要与使用隔离范围的指令一起工作。当然,这引起了此错误:

Multiple directives asking for new/isolated scope

我的代码看起来大致是这样:

html:

<p custom_directive='variable' vendor_directive>Test</p>

JS:

app.directive('ExampleDirective',function() {
    return {
        restrict: 'A',
        scope: {
            exampleDirective: '='
        },
        link: function(scope,element,attributes){
            // manipulate scope.exampleDirective
        }
    }
    });

我已经尝试完全从我的指示中删除范围,并在以下内容中使用一些内容:

scope.exampleDirective = scope.$eval(attributes.exampleDirective)

但是,这仅在对象上起作用,而我针对其他类型的变量。

如何实现?

我在这里可以看到的问题是,vendor_directive已经创建了一个孤立的范围,因此Angular不允许您在同一摘要周期中定义另一个孤立的范围。有两种解决此问题的方法 -

  • 首先和更复杂的是,您装饰了供应商指令以包括自定义指令的功能。这是更稳定和可信赖的方法。在这里浏览装饰器的文档

  • 第二和简单的方法是在属性上使用$ watcher.exampledirective变量并在每次更改时执行函数,以便模仿您想要

  • 的两种方式绑定

希望这有帮助

尝试以下:

app.directive('ExampleDirective',function() {
  return {
    restrict: 'A',
    bindToController: {
        exampleDirective: '='
    },
    scope: true,
    link: function(scope,element,attributes) {
        // manipulate scope.exampleDirective
    }
  }
});

最新更新