【发布时间】:2026-01-20 22:30:01
【问题描述】:
我正在使用Ionic Framework 构建一个应用程序,现在我想为其创建一些开关(基本上是花哨的复选框)。当一个人拨动开关时,我想将其发送到服务器,所以我首先尝试捕捉开关更改事件。在基本的角度安装中,我在 html (<input type="checkbox" ng-model="theswitch">) 中使用了一个简单的复选框,在我的控制器中使用了 $watch,如下所示:
$scope.$watch('theswitch', function(){
console.log('theswitch changed');
if ($scope.boel){
console.log('theswitch is TRUE');
} else {
console.log('theswitch IS FALSE');
}
});
这就像一个魅力。我现在在我的 Ionic 应用程序中实现了类似的东西。我的 HTML 是这样的:
<ion-item class="item-toggle">
Mail
<label class="toggle">
<input type="checkbox" ng-model="mail">
<div class="track">
<div class="handle"></div>
</div>
</label>
</ion-item>
我的控制器看起来像这样:
myControllers.controller('AccountCtrl', function ($scope) {
$scope.$watch('mail', function(){
console.log('THE MODEL CHANGED');
if ($scope.mail) {
console.log('The button was turned ON.');
} else {
console.log('The button was turned OFF.');
}
});
});
加载屏幕后,我得到两个日志:
THE MODEL CHANGED
The button was turned OFF.
之后我可以翻转开关一百万次,但我不再收到日志消息,甚至没有错误。由于它在我的角度测试网站中完美运行,但在我的应用程序中却没有,我有点迷失在可能的错误中。
有人知道我可以做些什么来捕捉这个 switch 事件吗?欢迎所有提示!
【问题讨论】:
-
你试过
$rootScope.$watch而不是$scope.$watch吗? -
@DawsonLoudon - 刚刚尝试过,但这也不起作用。还有其他建议吗? :S
标签: javascript angularjs cordova ionic-framework