外部 AngularJS 指令无法正确构建内部指令



使用 AngularJS 1.0.8,我正在尝试创建一些可重用的指令,以创建一种情况,即 Web 开发人员可以使用许多属性编写单个"顶级"指令,而该指令反过来又有一个包含其他指令的模板,这些指令本身可能包含其他指令等。

我遇到的问题是让"内部"模板知道顶级属性。我以为这将是一个普遍的问题,但从我的研究来看,似乎没有其他人在问这个问题。

我创建了这个 Plunker 来展示问题:

<!DOCTYPE html>
<html ng-app="outerInnerDirectivesApp">
<head>
    <title>Outer/Inner Directives</title>
</head>
<body>
<div>Single level directive follows:</div>
<single-level-directive single-level-id="single123"></single-level-directive>
<div>Outer/inner directive follows (Expecting "outer123"):</div>
<outer-directive outer-id="outer123"></outer-directive>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="app.js"></script>
<script src="directives.js"></script>
</body>
</html> 

在普伦克,

  1. 单级指令有效,我认为是一种显示数据的标准方式。

  2. 外部指令和内部指令不起作用。

我期望这些发生的事情是

(i) outerDirective编译/链接以生成html

<inner-directive inner-id="outer123"></inner-directive>

然后

(ii) innerDirective编译/链接以生成html

<div>outer123</div>

但是在第 (ii) 步,我得到

<inner-directive inner-id="" class="ng-isolate-scope ng-scope">
   <div class="ng-binding"></div>
</inner-directive>

所以一个空的div是由innerDirective生成的。

事实上,如果我更改外部模板.html

<div>{{outerId}}<div>

然后该值正确显示,因此看起来scope.outerId在正确的点可用,但Angular对我尝试以我的方式使用它感到不高兴。

这是期望 Angular 做的合理事情吗?如果是这样,我错过了什么?如果没有,那么您认为从简单的指令集构建更复杂的屏幕的明智替代方法是什么?

如果您要设计具有独立作用域的指令,我建议使用隔离作用域来定义要使用的属性类型:

outerInnerApp.directive("outerDirective", function() {
  return {
    restrict: "E",
    scope: {
      outerId: '@'
    },
    link: function(scope, element, attrs) {
    },
    templateUrl: "outer-template.html"
  };
});
outerInnerApp.directive("innerDirective", function() {
  return {
    restrict: "E",
    scope: {
      innerId: '='
    },
    link: function(scope, element, attrs) {
    },
    templateUrl: "inner-template.html"
  };
});

这是一个工作弹道。

外部指令正在使用属性中定义的值。 因此,要将值传递到隔离范围,我们可以使用 @ . 然后,内部作用域通过绑定变量。 因此,我们可以使用 = 来设置绑定属性。

对此有更多的想法。在使用 AngularJS 更多之后,我不确定是否要绑定到范围(使用"=")。事实上,我可以通过进行以下更改来使原始 Plunkr 工作:

outerInnerApp.directive("outerDirective", function() {
    return {
        restrict: "E",
        scope: {
        //add outerId here
        outerId: "@"
        },
    link: function(scope, element, attrs) {
        //remove scope assignment here
        //scope.outerId = attrs.outerId;
    },
    templateUrl: "outer-template.html"
    };
});
outerInnerApp.directive("innerDirective", function() {
    return {
    restrict: "E",
    scope: {
        //add innerId here
        innerId: "@"
    },
    link: function(scope, element, attrs) {
        //remove scope assignment here
        //scope.innerId = attrs.innerId;
    },
    templateUrl: "inner-template.html"
    };
});

我现在不明白的是,为什么两者之间有所不同,比如说,

innerId:"@"

并在链接函数中设置范围的值

link: function(scope, element, attrs) {
    scope.innerId = attrs.innerId;
}

当我发现为什么它的行为不同时,我会回发。

最新更新