假设我有一个图表指令(如饼图)和一个设置指令,其中包含用于修改图表指令设置的表单。 settings指令以模态对话框显示。
如何才能使设置指令中的更改在图表指令中生效?
可以有多个图表指令,每个指令都有独立的设置。每个图表的设置实际上将在设置模式中显示为选项卡,但我将其留下以保持示例简单。
以下是我尝试/考虑过的一些事情:
"使用工厂共享设置值。"这失败了,因为我可能有多个图表指令,每个指令都有不同的设置。
"让settings指令成为图表指令的子代。" settings指令不能是chart指令的子指令,因为它需要在模态中呈现。
Here is a plunkr以及一些相关摘要:
<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.
}
}
}
})
答案 0 :(得分:0)
尝试这个我希望它有所帮助:
<!DOCTYPE html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.11.2/ui-bootstrap-tpls.min.js"></script>
</head>
<body ng-app="app">
<div ng-controller="Controller">
<a href ng-click="showSettings()">Settings</a>
<chart></chart>
<chart></chart>
</div>
<script>
var app = angular.module("app", ['ui.bootstrap']);
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 () {
// This is where I need to modify the someChartSetting value from chart.
}
}
}
})
</script>
</body>
</html>