Javascript 当我们试图区分字符串时,Angular中的$Watch不起作用
我有一个AngularJs应用程序,我在一个服务上创建了watch 我在选项卡上有一个手表,每次单击都会检查是否选择了第二个选项卡。如果它是第二个标签,我正在做一些逻辑Javascript 当我们试图区分字符串时,Angular中的$Watch不起作用,javascript,angularjs,watch,Javascript,Angularjs,Watch,我有一个AngularJs应用程序,我在一个服务上创建了watch 我在选项卡上有一个手表,每次单击都会检查是否选择了第二个选项卡。如果它是第二个标签,我正在做一些逻辑 $scope.$watch('service.currentTab.getIndex() === 1', function (newValue, oldValue) { if (newValue !== oldValue) { if (newValue === true) {
$scope.$watch('service.currentTab.getIndex() === 1', function (newValue, oldValue) {
if (newValue !== oldValue) {
if (newValue === true) {
DO SOME LOGIC
}
}
});
它工作得很好
然而,在我看来,它并不优雅。如果将来有人在第二个位置添加一个标签,而不是这个标签,我的逻辑就会崩溃
为了修复它,我添加了enums.js文件:
var TabEnum = {
PAPERS: "PAPERS",
TELEPHONE: "TELEPHONE",
CELLPHONE: "CELLPHONE",
};
我的手表换成了:
$scope.$watch('service.getCurrentTabName() === TabEnum.TELEPHONE', function (newValue, oldValue) {
if (newValue !== oldValue) {
DO SOME LOGIC
}
});
Service.js:
app.service('service', [
function () {
this.getCurrentTabName = function(){
var currentTab = this.currentTab;
var currentTabName = currentTab.getTabName();
return currentTabName;
};
}
]);
为什么用这个短语
$scope.$watch('service.getCurrentTabName() === TabEnum.TELEPHONE'
不起作用?也向我们展示其余的相关代码:getAbName和相关html。我认为您的解决方案过于复杂。在我看来,如果你只设置一个标志来保存打开的标签上的信息,这个问题就可以解决得容易得多。或者每次点击你的电话标签时,就调用逻辑。我选择了按你说的做!谢谢