【发布时间】:2014-10-30 13:27:20
【问题描述】:
假设我有一个图表指令(如饼图)和一个设置指令,其中包含用于修改图表指令设置的表单。设置指令显示在模式对话框中。
如何使设置指令中的更改在图表指令中生效?
可以有多个图表指令,每个都有独立的设置。每个图表的设置实际上将在设置模式中显示为选项卡,但我将其省略以保持示例简单。
以下是我尝试过/考虑过的一些事情:
“使用工厂共享设置值。”这失败了,因为我可能有多个图表指令,每个都有单独的设置。
“让设置指令成为图表指令的子指令。” settings 指令不能是 chart 指令的子指令,因为它需要在 modal 中呈现。
Here is a plunkr 以及一些相关的 sn-ps:
<div ng-controller="Controller">
<a href ng-click="showSettings()">Settings</a>
<chart></chart>
<chart></chart>
</div>
JS:
app.controller("Controller", function ($scope, $modal) {
$scope.showSettings = function () {
$modal.open({
scope: $scope,
template: "<h1>Settings Modal</h1><settings></settings>"
}
);
}
});
app.directive("chart", function () {
return {
restrict: 'E',
template: '<h1>Chart Directive</h1><p>someChartSetting: {{someChartSetting}}</p>',
controller: function ChartController($scope) {
// This value represents a setting that I need to modify via the settings modal.
$scope.someChartSetting = "on";
}
}
})
app.directive("settings", function () {
return {
restrict: 'E',
template: '<a href ng-click="toggleSettings()">Toggle someChartSetting</a>',
controller: function SettingsController($scope) {
$scope.toggleSettings = function () {
console.log("Toggle clicked");
// This is where I need to modify the someChartSetting value from chart.
}
}
}
})
【问题讨论】:
-
你不能给每个图表一个唯一的ID,然后将设置存储在关联数组/对象内的工厂中,其中键与图表ID匹配吗?所以在你声明图表的地方,使用
-
我可以。我确实考虑过这一点,但感觉有点骇人听闻。这些指令半分散在更大的应用程序框架中,因此跟踪 ID 可能很烦人。我希望有一种方法可以直接将设置指令与图表指令连接起来。不过,您的建议会起作用。
-
没有 ID,这表明设置需要在 Chart 实例本身内部保存。也许值得构建一个 BaseModal 指令,然后有一个从 BaseModal 派生的 ChartSettingsModal。假设触发模式可见性的按钮存在于 Chart 指令中,那么您可以调用 ChartSettingsModal 控制器的 show 方法(通过 require 属性),其中包含所有相关设置。
-
设置保存在图表指令中。触发设置模式的按钮不在图表指令内,它在外面。用例是:带有单个设置模式的多个图表,以及该设置模式中的选项卡 - 每个图表实例 1 个选项卡。
标签: javascript angularjs angular-directive