AngularJS,范围,指令调用父控制器功能

时间:2014-05-08 12:15:12

标签: angularjs coffeescript directive

这到底是怎么回事?

我试图通过子指令调用父作用域控制器上定义的函数。由于某种原因'&'我失败了吗?

控制器&#h; html:

<div ng-controller="facetCtrl">
    <header>
        <div facet></div>
        <div facet></div>
    </header>
</div>

facet指令&lt; html:

<div ng-click="selectFacet($event)" notify="facetGroupSelected(facet)">
    <div>{{ name }}</div>
</div>

控制器的咖啡:

app = angular.module 'myApp', []

class facetCtrl

  constructor: (@$scope) ->
    @$scope[fn] = @[fn] for fn in [
      'facetGroupSelected'
    ]

  facetGroupSelected: (facetGroup) =>
    console.log(facetGroup)

app.controller 'facetCtrl', [
  '$http'
  facetCtrl'
]

指令的咖啡:

app = angular.module 'myApp'

facetDirective = ->
  replace: true
  restrict: 'A'
  templateUrl: '..path/to/template'
  scope:
    notify: '&'
  link: (scope, element, attrs) ->
    scope.selectFacet = ($event) ->
      scope.notify('someFacetGroup')

app.directive 'facet', [
  'facetDirective'
]
但是,在某些地方,我的函数参数正在被删除。来自指令的函数调用触发了父控制器的功能,但就像我说的那样,参数不能成功。咖啡范围(__bind.apply等)是否会破坏某些内容?

1 个答案:

答案 0 :(得分:1)

调用notify时,您需要以稍微不同的方式指定参数:

$scope.notify( { facet: 'someFacetGroup' } );