首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角指令作用域内部属性继承

角指令作用域内部属性继承
EN

Stack Overflow用户
提问于 2015-01-29 13:30:10
回答 1查看 51关注 0票数 2

AngularJS新手问题。我想写个密谋指令。假设我有这个:

代码语言:javascript
复制
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" },
        ...
        ];
});

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

代码语言:javascript
复制
<my-plot xLabel="Some Numbers" xUnits="grams"
                    yLabel="Some Values"  yUnits="mm"
                    data="datapoints" />

我的问题是“数据点”没有绑定到$scope.datapoints --我也尝试过以data="{{datapoints}}"的形式编写属性,但也没有成功。

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

代码语言:javascript
复制
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 */
          };
    });

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-29 13:48:14

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

下面是来自AngularJS正式文件的一个例子。

代码语言:javascript
复制
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通过继承访问控制器中的变量。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28215993

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档