【问题标题】:Angularjs - Calling a controller function inside directiveAngularjs - 在指令内调用控制器函数
【发布时间】:2015-07-29 08:03:45
【问题描述】:

我正在尝试将 jQuery Sparkline 图表与 Angularjs 一起使用。我有多个图表要显示,所以我决定在控制器中创建一个函数并为每个图表(指令)调用它。

JS

控制器

.controller('sparklineCtrl', [function(){

     this.sparklineBar = function(id, values, height, barWidth, barColor, barSpacing) {
           $('.'+id).sparkline(values, {
                type: 'bar',
                height: height,
                barWidth: barWidth,
                barColor: barColor,
                barSpacing: barSpacing
           })
      }

}])

指令

.directive('sparklineBar', function(){

        return {
            restrict: 'A',
            scope: {
                slBar: '&'
            },
            link: function(scope, element) {
                scope.slBar('stats-bar', [6,4,8,6,5,6,7,8,3,5,9,5,8,4,3,6,8], '45px', 3, '#fff', 2);
            }
        }

    })

HTML

<div data-ng-controller="sparklineCtrl as spctrl">
      <div class="chart" id="stats-bar" data-sparkline-bar data-sl-bar="spctrl.sparklineBar()"></div>                                  
</div>

运行上面的代码,浏览器控制台没有错误,但它根本没有渲染图表。我不知道我的代码有什么问题。当我尝试将函数的代码直接放在指令中时,它正在工作。

.directive('sparklineBar', function(){

        return {
            restrict: 'A',
            link: function(scope, element) {
                $('#stats-bar').sparkline([6,4,8,6,5,6,7,8,3,5,9,5,8,4,3,6,8], {
                    type: 'bar',
                    height: 45,
                    barWidth: 3,
                    barColor: '#fff',
                    barSpacing: 2
                })
            }
        }

    })

我不想使用上述方式,因为我需要多个图表。请帮助我使用控制器功能解决此问题。

【问题讨论】:

  • 指令让您可以访问element,当 jQuery 包含在 Angular 之前的页面中时,这将是 jQuery 对象。使用它而不是 id 选择器。 jQuery 不属于控制器,而是将数据传递给指令
  • 在指令中指定你的控制器。 controller: 'sparklineCtrl', controllerAs: 'spctrl'

标签: javascript angularjs angularjs-directive


【解决方案1】:

最好将功能逻辑移动到服务/工厂中,然后在指令中使用注入。

例子:

app.factory('sparkService', function () {
 var ss = {} ; 
 ss.slBar= function(id, values, height, barWidth, barColor, barSpacing) {
       $('.'+id).sparkline(values, {
            type: 'bar',
            height: height,
            barWidth: barWidth,
            barColor: barColor,
            barSpacing: barSpacing
       });
 };

 return ss;
}

在指令中

.directive('sparklineBar', ['sparkService',function(sparkService){

    return {
        restrict: 'A',
        scope: {
            slBar: '&'
        },
        link: function(scope, element) {
            sparkService.slBar('stats-bar', [6,4,8,6,5,6,7,8,3,5,9,5,8,4,3,6,8], '45px', 3, '#fff', 2);
        }
    }]);

【讨论】:

  • 感谢您的回复。我试过你的方法,但没有运气。我应该在 HTML 和 data-sparkline-bar 旁边调用什么?是不是类似于 data-sl-bar='....' ?
  • 请忽略我上面的回复,它运行良好。再次非常感谢您。
猜你喜欢
  • 2021-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多