一个元素的多个指令可以共享一个隔离的范围吗?

问题描述:

同一元素上的两个指令不能都具有独立的作用域,但它们可以使用与父元素隔离的相同作用域吗?它们都可以使用绑定到隔离作用域的属性吗?

Two directives on the same element can not both have isolated scope, but can they both use the same scope isolated from their parent? And can they both use properties bound to the isolated scope?

例如,如果我在一个元素上有两个指令

For example, if I have two directives on an element

<e-directive a-directive prop="parentProp"/>

并且一个指令定义了一个具有绑定属性的隔离作用域

And one directive defines an isolated scope with a bound property

App.directive('eDirective', function() {
  return {
    restrict: 'E',
    scope: {
      localProp: '=prop'
    },
    ...
  };
});

其他指令是否获得该范围并且它可以使用绑定属性?

Does the other directive get that scope and can it use the bound property?

App.directive('aDirective', function() {
  return {
    restrict: 'A',
    link: function postLink(scope, element, attrs) {
        scope.$watch('localProp', function(newProp, oldProp) {
          ...
        }
    },
    ...
  };
});

我最初的尝试(大致如上编码)失败了.

My initial attempt (pretty much coded as above) failed.

我建议您通过辅助指令的 require 属性在指令的控制器之间进行通信.第一个指令 (e-directive) 持有隔离的作用域,而第二个辅助指令 (a-directive) 引用第一个指令并通过在第一个指令上定义的函数设置属性.一个小样本是(参见plunker):

I suggest you make use of communicating between the directives' controllers via the require property of the secondary directive. The first directive (e-directive) holds the isolated scope, while the second helper directive (a-directive) has a reference to the first directive and sets properties via functions defined on the first directive. A small sample would be (see plunker):

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <div e-directive config="parentConfig" a-directive></div>
  </body>

</html>

和 javascript:

and the javascript:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.parentConfig = {};
});

app.controller('ECtrl', function ( $scope ) {
  this.setProp = function(newProp){$scope.config.prop = newProp;};

  $scope.$watch('config', function(newProp, oldProp) {
    console.log(oldProp, newProp);
  });
});

app.directive('eDirective', function() {
  return {
    restrict: 'A',
    scope: {
      config: '='
    },
    controller: 'ECtrl',
    link: function(scope, element, attrs) {
      scope.config.prop ="abc";
    }
  };
});

app.directive('aDirective', function() {
  return {
    restrict: 'A',
    require: 'eDirective',
    link: function(scope, element, attrs,ctrl) {
        ctrl.setProp("def");
    }

  };
});