2015-01-11 93 views
1

在本例中改變範圍對象我有三個範圍中的對象依賴於其他範圍可變

$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很多項目的多刪節版。)

+0

你是否意識到你根本不需要任何$ watch,因爲你可以使用對象引用? – dfsq

+0

使用引用來利用繼承。象:'$ scope.theme = $ scope.themes [0]'...'$ {scope.config someProperty:$ scope.theme.propertyName}' – charlietfl

回答

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

的想法是,任何人都可以叉這個項目,並建立了自己的config(它最終會被抽象成某個接口或服務),這意味着'$ scope.theme'屬性需要保留在'$ scope.config'中,以便人們能夠設置自己的主題來改變特定的他們需要的屬性。 – Htch