mainApp有两个具有不同功能的控制器。它们的一些功能很常见。
mainApp.controller("WriteController", function($scope) {
$scope.$watch('task.file.prefix', function (term) {
term = term.replace(/\\/g,'/');
$scope.task.file.prefix = term;
});
});
mainApp.controller("ReadController", function($scope) {
$scope.$watch('task.file.prefix', function (term) {
term = term.replace(/\\/g,'/');
$scope.task.file.prefix = term;
});
});
你可以清楚地看到我正在为两个控制器使用两个手表(相同)。有没有办法让我们将这些$ watch从控制器移出到外面的某个地方(服务等)来满足DRY。
答案 0 :(得分:1)
不确定某人是否有更好的解决方法但你可以试试这个
mainApp.service('watcher', function(){
return {
term : function (newValue) {
// we don't need scope here because newValue is the scope being watched.
// newValue changed = equivalent of $scope. being watch changed.
newValue = newValue.replace(/\\/g,'/');
}
}
})
mainApp.controller("WriteController", function($scope, watcher) {
// passing the function (do not execute it)
$scope.$watch('task.file.prefix', watcher.term);
});
mainApp.controller("ReadController", function($scope, watcher) {
// passing the function (do not execute it)
$scope.$watch('task.file.prefix', watcher.term);
});