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

Javascript 更改依赖于另一个范围变量的范围对象,javascript,angularjs,scope,watch,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

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

$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选择
更新
$scope.theme
(使用
$scope.themes
作为
ng选项
)的值。当
$scope.theme
更改时,我想更新
$scope.config
的值,其中一些属性依赖于
$scope.theme
的值

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

$scope.theme
更改时,如何触发对
$scope.config
的更新,以触发我的
$watch


(值得注意的是,上面是一个经过大量编辑的
$scope.config
,其中
config.elements
中有许多项)

您可以从配置中排除主题属性,同时查看指令主题和配置

配置:

$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;
    ...
});

您是否意识到您根本不需要任何$watch,因为您可以使用对象引用?使用引用可以利用继承。例如:
$scope.theme=$scope.themes[0]
$scope.config{someProperty:$scope.theme.propertyName}
想法是任何人都可以参与这个项目并建立自己的配置(最终将抽象为一些接口或服务),这意味着
$scope.theme
属性需要保留在
$scope.config
中,以便人们能够设置自己的主题来更改所需的特定属性。