gpt4 book ai didi

angularjs - 如何绑定(bind)到指令属性?

转载 作者:行者123 更新时间:2023-12-02 07:21:15 25 4
gpt4 key购买 nike

我希望高图的标题是 $scope.data.title 但目前属性标题将 data.title 解释为字符串并绑定(bind)到范围.我试过将 "", {{}} 放在 .html 的 data.title 周围,但它不起作用。我想我还缺少其他东西。

index.html

  <test-chart title="{{data.title}}">
<chart-series title="Series 1" type="line">
</chart-series>
<chart-series title="Series 3" type="column">
</chart-series>
</test-chart>

script.js

  .directive('testChart', function() {
return {
restrict: 'E',
transclude: true,
controllerAs:'chartCtrl',
scope: {
},
controller: ['$scope', '$element', '$attrs', function ChartController($scope, $element, $attrs) {

$scope.data = {
title: 'HIGHGRAPH',
series: [{
title: 'series1',
type: 'line',
data: [1,2]
}, {
title: 'series2',
type: 'area',
data: [3,5]
}]
}

var hc = Highcharts.chart('highchart_container', {});

$scope.$watch("data",function(newValue,oldValue) {

hc.update({
title: {
text: newValue.title
}
})
})

this.addSeries = function(a) {

hc.addSeries({
name: a.title,
type: a.type,
data: [1,2,3,4,5,6]
})
};
}],
templateUrl: 'my-tabs.html'
};

编辑:https://plnkr.co/edit/spUAkCjK61HgUGu40pZl?p=preview

这没有按预期工作,但是否可以在没有 watch 的情况下执行此操作?

最佳答案

您不必将 s.title 放在 ng-repeat 中。它应该在外面。这是一个工作片段。:-

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
});

app.directive('testChart', function() {
return {
restrict: 'E',
transclude: true,
controllerAs:'chartCtrl',
scope: {
},
controller: ['$scope', '$element', '$attrs', function ChartController($scope, $element, $attrs) {

$scope.data = {
title: 'HIGHGRAPH',
series: [{
title: 'series1',
type: 'line',
data: [1,2]
}, {
title: 'series2',
type: 'area',
data: [3,5]
}]
}

var hc = Highcharts.chart('highchart_container', {
title: {
text: $scope.data.title
}
});

this.addSeries = function(a) {

hc.addSeries({
name: a.title,
type: a.type,
data: [1,2,3,4,5,6]
})
};
}],
template: '<div> <p>This is a chart</p><ul> <li ng-repeat="s in series"> </li> </ul> <div id=\'highchart_container\'></div> <ng-transclude></ng-transclude> </div>'
};
})
.directive('chartSeries', function() {
return {
require: '^test-chart',
restrict: 'E',
transclude: true,
scope: {
title: '@'
},
link: function(scope, element, attrs, chartCtrl) {
chartCtrl.addSeries(attrs);
},
};
});
#highchart_container{
height:250px!important;
}
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<test-chart title="Custom title">
<chart-series title="Series 1" type="line">
</chart-series>
<chart-series title="Series 3" type="column">
</chart-series>
</test-chart>

</div>

关于angularjs - 如何绑定(bind)到指令属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45323090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com