更改依赖于另一个范围变量的范围对象

时间:2015-01-11 18:39:19

标签: javascript angularjs scope watch

在这个例子中,我有三个范围对象

$scope.themes = [
  {
    name: 'Theme 1',
    backgroundColor: '#000000',
  },
  {
    name: 'Theme 2',
    backgroundColor: '#FFFFFF',
  },
];

$scope.theme = {
  name: 'Default Theme',
  backgroundColor: '#000000',
};

$scope.config = {
  canvas: {
    fill: $scope.theme.backgroundColor,
  },
  elements: [
    {
      name: 'Circle',
      width: 200,
      height: 1000,
      fill: $scope.theme.backgroundColor
    },
  ]
};

ng-select更新$scope.theme的值(使用$scope.themes作为ng-options)。当$scope.theme发生变化时,我想更新$scope.config的值,其中某些属性取决于$scope.theme的值。

$scope.config通过一个指令在其上运行$watch(),该指令对视图中的元素进行更改,因为可以通过界面更改许多编辑的属性。

如果$scope.config发生变化,如何触发对$scope.theme的更新,以便触发$watch

(值得注意的是,上面是$scope.config的编辑版本很多,其中config.elements内有很多项目。)

1 个答案:

答案 0 :(得分:0)

您可以从配置中排除主题属性,并在指令主题中同时观看并配置。

配置:

$scope.config = {
  canvas: {
  },
  elements: [
    {
      name: 'Circle',
      width: 200,
      height: 1000
    },
    ...
  ]
};

你的指令:

...
$scope.$watch('[theme, config]', function() {
    //do what you want with elements considering theme and config
}, true);

如果您不想从配置中排除主题属性,则可以分别观看主题和更改配置

$scope.$watch('theme', function(theme) {
    $scope.config.canvas.fill = theme.backgroundColor;
    ...
});
相关问题