【问题标题】:Changing scope object that depends on another scope variable更改依赖于另一个范围变量的范围对象
【发布时间】:2015-03-09 13:13:14
【问题描述】:

在这个例子中,我有三个作用域对象

$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.theme 更改时,如何触发对$scope.config 的更新,以触发我的$watch

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

【问题讨论】:

  • 您是否意识到您根本不需要任何 $watch ,因为您可以使用对象引用?
  • 使用引用来利用继承。喜欢:$scope.theme = $scope.themes[0] ... $scope.config{ someProperty: $scope.theme.propertyName}

标签: javascript angularjs scope watch


【解决方案1】:

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

配置:

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

【讨论】:

  • 这个想法是任何人都可以分叉这个项目并设置他们自己的配置(最终将被抽象成一些接口或服务),这意味着$scope.theme属性需要保留在@987654325中@ 以便人们能够设置自己的主题来改变他们需要的特定属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-05
  • 1970-01-01
  • 2013-05-29
相关资源
最近更新 更多