属性内的角度指令范围继承

Angular Directive scope inheritance inside attributes

本文关键字:指令 范围 继承 属性      更新时间:2023-09-26

AngularJS新手问题。我想写一个绘图指令。假设我有这个:

app.controller("dirCtrl", function($scope) {
    $scope.datapoints = [
        { x: 1.169, y: 1.810, label: "Point-0" },
        { x: 1.585, y: 0.508, label: "Point-1" },
        { x: 7.604, y: 2.735, label: "Point-2" },
        ...
        ];
});

那么我希望我的指令是这样的:

<my-plot xLabel="Some Numbers" xUnits="grams"
                    yLabel="Some Values"  yUnits="mm"
                    data="datapoints" />

我的问题是"数据点"没有绑定到$scope.datapoints我也尝试将属性编写为data="{{datapoints}}"也没有成功。

我的指令定义,在其自己的模块中:

angular.module("plotDirectives", [])
  .directive("myPlot", function() {
     return {
          restrict: "E",
          scope: true,  //'cos I want access to the controller's scope right?
          link: function(scope, iElement, iAttrs) {
            /* would draw fancy chart if I only could access
               the datapoints in the 'data' attribute */
          };
    });

我缺少什么,或者我的指令获取控制器范围数据点的更好方法是什么?谢谢。

您可以在指令中使用隔离作用域。

这是来自AngularJS官方文档的示例。

angular.module('docsIsolateScopeDirective', [])
.controller('Controller', ['$scope', function($scope) {
  $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
  $scope.igor = { name: 'Igor', address: '123 Somewhere' };
}])
.directive('myCustomer', function() {
  return {
    restrict: 'E',
    scope: {
      customerInfo: '=info'
    },
    templateUrl: 'my-customer-iso.html'
  };
});

<div ng-controller="Controller">
  <my-customer info="naomi"></my-customer>
  <hr>
  <my-customer info="igor"></my-customer>
</div>

如果你在指令中使用scope: true(这在大多数情况下是一种不好的做法,因为它使指令与控制器非常紧密地耦合),你不需要在 DOM 上为你的指令设置属性,只需使用 scope.yourVariableName 通过继承访问控制器中的变量。