AngularJS:如何从指令访问范围

时间:2014-02-07 16:45:52

标签: angularjs-directive angularjs-scope

我正在使用指令来绘制图表:

drawGraph.directive "graph", ->
  restrict: "E" # Use as element
  scope: # Isolate scope
    data: "=" # Two-way bind data to local scope
    opts: "=?" # '?' means optional

  template: "<div></div><div id='{{graph.id}}'></div>" # We need a div to attach graph to
  link: (scope, elem, attrs) ->
    graph = new Dygraph(elem.children()[0], scope.data, scope.opts)

虽然

<div id='{{graph.id}}'>

实际上在partial中工作,它返回

<div id></div>

当我在指令的模板中使用它时。谁能告诉我为什么?

更新

在暗示了@Marek后,我的指示现在看起来像这样:

drawGraph.directive "graph", ->
    restrict: "E" # Use as element
    scope: # Isolate scope
        data: "=" # Two-way bind data to local scope
        opts: "=?" # '?' means optional

    template: "<div></div><div class='legend'></div>" # We need a div to attach graph to
    link: (scope, elem, attrs) ->
        scope.opts.labelsDiv = elem.children()[0].getElementsByClassName("legend")[0]
        scope.graph = new Dygraph(elem.children()[0], scope.data, scope.opts)

选项在控制器中添加:

drawGraph.controller "MyCtrl", [ "myService", "$scope", (myService, $scope) -> 
    myService.async().then (d) ->
        rawData = d
        group = rawData

        i = 0
        while i < group.length
            j = 0
            while j < group[i].data.length
            # Convert date
            tmp = new Date(group[i].data[j][0])
            group[i].data[j][0] = tmp
            # Set draw options
            group[i].opts = 
                labels: [ "x", "Your Price", "Market Price" ],
                customBars: true,
                labelsSeparateLines: "true",
                hideOverlayOnMouseOut: false,
                legend: "always",
                showRangeSelector: true,
                xAxisLabelWidth: 80,
            ++j
        ++i
$scope.graphs = group

2 个答案:

答案 0 :(得分:1)

问题是隔离范围默认情况下无法访问父范围,因此需要在指令范围内定义“id”。

drawGraph.directive "graph", [(graph) ->
restrict: "E"
scope:
    data: "="
    opts: "=?"
    id: "="

答案 1 :(得分:0)

您实际上并未将图表放入范围。 最后一行应该是:

scope.graph =新的Dygraph(elem.children()[0],scope.data,scope.opts)