javascript 离子 - AngularJS:离子切换不更新模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29790767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ionic - AngularJS : ion-toggle doesn't update the model
提问by noli
I have a strange issue with the ion-toggle directive in Ionic framework.
我对 Ionic 框架中的 ion-toggle 指令有一个奇怪的问题。
When using ion-toggle like this :
当像这样使用 ion-toggle 时:
<ion-toggle ng-model="testToggle">Test toggle</ion-toggle>
JS:
JS:
$scope.$watch('testToggle',function(value) {
console.log('testToggle changed to '+value);
})
The controller doesn't receive any update at all.
控制器根本没有收到任何更新。
Here's the CodePen : http://codepen.io/anon/pen/jPOMqz
这是 CodePen:http://codepen.io/anon/pen/jPOMqz
You'll see that i've added an $interval that changes a binded variable to random in order to see that everything else works as expected
您会看到我添加了一个 $interval 将绑定变量更改为 random 以查看其他所有内容是否按预期工作
Thank you very much :)
非常感谢你 :)
回答by Keval
I used ng-change
to detect a change; and I am calling the function toggleChange()
upon a change. So your ion-toggle
will look like:
我曾经ng-change
检测到变化;我toggleChange()
在更改时调用该函数。所以你ion-toggle
会看起来像:
<ion-toggle ng-model="value" ng-change="toggleChange()">Test toggle</ion-toggle>
And your controller will change the $scope.value
and hence you'll get the toggle's value from $scope.value
:
并且您的控制器将更改$scope.value
,因此您将从以下位置获得切换的值$scope.value
:
.controller('ContactCtrl', function($scope, $interval) {
$scope.value = false;
console.log('ContactCtrl started');
$scope.toggleChange = function() {
if ($scope.value == false) {
$scope.value = true;
} else
$scope.value = false;
console.log('testToggle changed to ' + $scope.value);
};
}
Here's the Codepen for the same: http://codepen.io/keval5531/pen/LVYROp
这是相同的 Codepen:http://codepen.io/keval5531/pen/LVYROp
回答by Ishan Thilina Somasiri
The answer by Keval didn't work for me because he's resetting the value of the model, which puts the toggle button to its original position. So the proper answer would be to create a toggle like the following.
Keval 的答案对我不起作用,因为他正在重置模型的值,这会将切换按钮置于其原始位置。所以正确的答案是创建一个如下所示的切换。
<ion-toggle ng-model=value ng-change="toggleChange()">Test toggle</ion-toggle>
<ion-toggle ng-model=value ng-change="toggleChange()">Test toggle</ion-toggle>
And then write the controller as follows.
然后编写控制器如下。
.controller('ContactCtrl', function($scope, $interval) {
$scope.value = false;
$scope.toggleChange = function() {
console.log('testToggle changed to ' + $scope.value);
};
}