Skip to content

Instantly share code, notes, and snippets.

@WalterInSH
Created July 14, 2015 10:44
Show Gist options
  • Save WalterInSH/e32611c2b71682aa6e29 to your computer and use it in GitHub Desktop.
Save WalterInSH/e32611c2b71682aa6e29 to your computer and use it in GitHub Desktop.
angularjs watch list. avoid duplicated watching
$scope.watcher_switches = [];
$scope.add_status_watcher = function () {
//stop watching
angular.forEach($scope.watcher_switches, function (value) {
value();
});
//bind new watchers
var new_watchers = [];
for(var key in $scope.rule_sets) {
if($scope.rule_sets.hasOwnProperty(key)) {
var watcher_switch = $scope.$watch("rule_sets['" + key + "']", function(newValue, oldValue) {
if (newValue !== oldValue &&
newValue.status != oldValue.status) {
if (newValue.status == 'ON') {
$http.put('/api/rule_set/enable?id=' + newValue.id);
} else {
$http.put('/api/rule_set/disable?id=' + newValue.id);
}
}
},true);
new_watchers.push(watcher_switch);
}
}
//replace previous watcher array
$scope.watcher_switches = new_watchers;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment