我正在使用 Ionic Framework 构建应用程序我现在想为此创建一些开关(基本上是花哨的复选框)。当有人按下开关时,我想将其发送到服务器,因此我首先 try catch 开关更改事件。在基本的 Angular 安装中,我在 html ( <input type="checkbox" ng-model="theswitch">
) 和 $watch
中使用一个简单的复选框进行了尝试。在我的 Controller 中像这样:
$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>
我的 Controller 看起来像这样:
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.
在那之后我可以翻转开关一百万次,但我再也没有收到日志消息,甚至没有错误。由于它在我的 Angular Testing 网站上运行良好,但在我的应用程序中却不行,所以我有点迷失在可能出错的地方。
有人知道我可以做些什么来捕捉这个切换事件吗?欢迎所有提示!
最佳答案
不工作的可能原因 $scope.$watch
可能是子作用域中的属性覆盖。如果您在 Controller 作用域上设置了 $watch
,但是带有 ng-model
绑定(bind)的复选框是在 Controller 的某个子作用域内创建的,子作用域可能会创建自己的 mail
属性和 Controller $scope.$watch 将无法检测到该属性的变化。这是演示此问题的 jsfiddle:link .
为避免此问题,您不应在 ng-model
绑定(bind)的作用域上使用原始值。相反,您应该绑定(bind)到范围内对象的属性,例如 ng-model="formData.mail"
其中 formData
是 Controller 范围内的某个对象。要监视对象属性更改,您还可以使用点语法:$scope.$watch('formData.mail', function(){...})
希望这对您有所帮助。
关于javascript - $scope.$watch in Angular 在 Ionic/Cordova 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29127168/