在子指令中使用指令中的对象

Use object from directive inside child directive

我有两个指令。外部指令需要从服务中获取一些信息,然后将该对象用于内部指令。但我不知道如何正确地做到这一点。下面是一些示例代码,其中我假设我有一些彩色铅笔,我们需要根据 ID 检索铅笔信息以确定铅笔的颜色:

<div pencil-directive pencil-id="7"></div>

angular.module('app', [])

.controller('sampleController', function($scope){
  $scope.color = "red";
})

.directive('colorDirective', function(){
  return {
    restrict: "E",
    template: "<span ng-class='color'>{{color}}</span>",
    scope: {
      color: '='
    }
  }
})

.directive('pencilDirective', ["$timeout", function($timeout){
  return{
    restrict: "A",
    template: "<div>Pencil {{pencilId}} is " +
      "<color-directive color='pencil-color'> </div>",
    scope: {
      pencilId: "@",
      pencilColor: "=?"
    },
    controller: function($scope){
      //simulate getting the pencil color from a service
      $timeout(function(){
        $scope.pencilColor = "blue";
      }, 10)

    }
  }
}])

我希望它看起来像这样:

Pencil 7 color is blue.

但它最终看起来像这样:

Pencil 7 color is 0

我认为那是因为 pencilColorcolorDirective 看到它时没有初始化并且以后也没有更新,但我不知道 "angular way"使这项工作。

Here's a plunk. 请注意,我使用的是 Angular 1.2,因为我们仍然支持 IE 8(目前)。

您的问题是您的父指令和子指令之间的绑定方式。

您使用 scope.pencilColour,但使用 pencil-color 将其传递到您的子指令中。

为指令使用作用域特性和属性时,需要使用破折号。但是,当在您的模板中使用它们进行绑定时。使用 {{}} 或将它们传递到子指令属性中,您不需要破折号并且可以使用定义的范围 属性。

所以把<color-directive color='pencil-color'> </div>改成<color-directive color='pencilColor'> </div>

请参阅插件:http://plnkr.co/edit/mVCKLWgknwg81SUkIRtf?p=preview


编辑: 不太确定我是否解释得很好,也许这会有所帮助。

<!--Here we need the dash as were referencing it as a html attribute-->

<div pencil-directive pencil-color="'green'"></div>

<!--However in the directives template when we bind we use it as defined on our scope-->

{{pencilColor}}

<!--Even when passing it into a sub directive. The sub directives attribute needs the dash but our current one doesn't.-->

<sub-directive sub-prop="pencilColor" />