繁体   English   中英

如何在angular js中制作自定义指令或在指令中传递变量

[英]how to make custom directive or pass variable in directive in angular js

我正在尝试以角度制作条形图。我能够在 jquery 中制作(使用 highchart.js 文件)。这是我能够在jquery代码中制作的链接http://plnkr.co/edit/SD1iSTBk8o1xi3unxKeE?p =preview .我得到了正确的输出。但是我需要使用指令使用angularjs来显示同样的事情。所以我尝试制作指令。我的问题是我将如何在指令中传递我的参数

这是我的角度代码 http://plnkr.co/edit/LwonlkbCy3asHXyToVMz?p=catalogue

// Code goes here

angular.module('contactsApp', ['ionic'])
.controller('MainCtrl', function($scope) {

}).directive('chartTest',function(){
  return {
    restrict: 'E',
    scope:{

    },
    link :function(scope, element, attrs){
      element.highcharts({
        chart: {
            type: 'bar'
        },
        title: {
            text: chart_title
        },
        xAxis: {
            categories: xAxisarry
        },
        yAxis: {
            title: {
                text: 'Fruit eaten'
            }
        },
        series: [{
            name: names[0],
            data: janeData
        }, {
            name: names[1],
            data: joneData
        }]
    });
    }


  }

});

我希望它看起来像在 jquery 中一样吗? 我们可以使用范围在指令中传递变量吗?

您需要从指令的隔离范围传递参数,然后在指令中您需要在指令元素上使用$以使highcharts方法可用。

标记

<chart-test chart-title="chartTitle" x-axisarry="xAxisarry" 
y-axis="yAxis" json-data="janeData" names="names"></chart-test>

控制器

.controller('MainCtrl', function($scope) {
    $scope.chartTitle = "";
    $scope.xAxisarry = ['Apples', 'Bananas', 'Oranges'];
    $scope.yAxis = 'Fruit eaten';
    $scope.data = {
      jane: [1, 0, 4],
      jone: [5, 7, 3]
    };
    $scope.names = ["jane", "jone"];

})

指示

.directive('chartTest', function() {
    return {
      restrict: 'E',
      scope: {
        chartTitle: '=',
        xAxisarry: '=',
        yAxis: '=',
        jsonData: '=',
        names: '='
      },
      link: function(scope, element, attrs) {
        $(element).highcharts({
          chart: {
            type: 'bar'
          },
          title: {
            text: scope.chartTitle
          },
          xAxis: {
            categories: scope.xAxisarry
          },
          yAxis: {
            title: {text: 'Fruit eaten'}
          },
          series: [{
            name: scope.names[0],
            data: scope.jsonData['jane']
          }, {
            name: scope.names[1],
            data: scope.jsonData['jone']
          }]
        });
      }
    }
});

工作Plunkr

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM