angularjs:指令

时间:2015-06-22 09:46:34

标签: javascript angularjs angularjs-directive angularjs-controller angular-directive

我的指令中有一个函数绑定到我的控制器中的函数,如下所示:

HTML:

<div graph-visualization data="graphdata" type="graphtype" data-method="watchMonth" timespan="timespan" id="graph" ng-if="!loading">
</div>

指令:

app.directive('graphVisualization', function() {
    return {
        restrict: 'A',
        scope: {
          data: '=',
          type: '=',
          timespan: '=',
          monthFilter: '&method'
        },
        link: function(scope, element, attrs) {
            scope.updateMonth = function() {
                var func = scope.monthFilter();
                func(scope.month)
            }

            scope.$watchGroup(['data', 'timespan', 'type'], function(newval, oldval) {
                 scope.month = 'something'
                 scope.updateMonth()
            })
})

控制器:

$scope.watchMonth = function(value) {
    //handle value passed from directive
}

正如你所看到的,我的控制器中有一个绑定函数'watchMonth',它是从指令中调用的。 现在,我想在我的指令中添加另一个函数,该函数绑定到我的控制器中的其他函数。我该怎么办呢?似乎无法理解它。

我想要的是我在我的指令中处理点击并根据该点击获取值。现在,我想将此值传递给控制器​​,控制器将在控制器中修改“graphdata”(我在其上提供了一个watchgroup)。

1 个答案:

答案 0 :(得分:1)

在html中添加如下所示的方法: 月滤波器=&#34; watchMonth()&#34;第二功能=&#34;()的函数&#34;

请务必在功能名称末尾添加括号

  <div graph-visualization data="graphdata" type="graphtype" month-filter="watchMonth()" second-function="secondFunction()" timespan="timespan" id="graph" ng-if="!loading">

app.directive('graphVisualization', function() {
return {
    restrict: 'A',
    scope: {
      data: '=',
      type: '=',
      timespan: '=',
      monthFilter: '&',
      secondFunction: '&'
    },
    link: function(scope, element, attrs) {
        scope.updateMonth = function() {
            var func = scope.monthFilter();
            func(scope.month)
        }

        scope.$watchGroup(['data', 'timespan', 'type'], function(newval, oldval) {
             scope.month = 'something'
             scope.updateMonth()
        })

})

添加了一个plunker,也许这会帮助你 http://plnkr.co/edit/cISSlQpQF6lFQrDdbTg4?p=preview