比方說,我有一個圖表指令(如餅圖)和一個包含用於修改圖表指令設置的表單的設置指令。設置指令顯示在模態對話框中。從單獨的指令修改指令範圍中的值
如何使設置指令中的更改在圖表指令中生效?
可以有多個圖表指令,每個圖表指令都有獨立的設置。每個圖表的設置實際上都會在設置模式中顯示爲選項卡,但爲了保持示例簡單,我省略了這些設置。
這裏有一些事情我已經試過/考慮:
「使用工廠共享的設置值。」這失敗了,因爲我可能有多個圖表指令,每個都有獨立的設置。
「讓設置指令成爲圖表指令的子項。」設置指令不能是圖表指令的子元素,因爲它需要在模態中呈現。
Here is a plunkr沿W /一些相關片段:
<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.
}
}
}
})
你能不能給每個圖表au nique ID,然後將設置存儲在關聯數組/對象內的工廠內,其中鍵與圖表ID相符?所以在你申報圖表的地方,可以使用 –
romiem
2014-10-31 11:16:06
。我確實考慮到了這一點,但感覺有點ha。。這些指令是分佈在更大的應用程序框架中的,因此跟蹤ID可能會令人討厭。我希望能夠直接將設置指令與圖表指令相連接。你的建議雖然會起作用。 – 2014-10-31 13:33:04
沒有ID,這表明這些設置需要保存在Chart實例本身的內部。也許值得建立一個BaseModal指令,然後有一個從BaseModal派生的ChartSettingsModal。假設用於觸發模式可見性的按鈕存在於Chart指令中,則可以調用ChartSettingsModal控制器的show方法(通過require屬性),其中包含所有相關設置。 – romiem 2014-10-31 13:58:05