angularjs:指令中的多个绑定函数

angularjs: multiple binded functions in directive

本文关键字:绑定 函数 指令 angularjs      更新时间:2023-09-26

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

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"(我在上面提供了一个观察组)。

在html中添加如下方法:month filter="watchMonth()"second function="function()"

请确保在函数名的末尾添加括号

  <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