我是 AngularJS/Ionic 的新手,我正在尝试检测输入类型 =“范围”的值的变化,并根据此值在 js 中执行操作。
但我不确定如何检测它:$watch 还是 ng-change?
代码如下: HTML:
<html ng-app="SnowBoard">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Checkboxes</title>
<link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
<script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
</head>
<body ng-controller="ComputeCtrl">
<ion-content>
<div class="range">
<input id="levelrange" type="range" min="0" max="10" value="5" name="userlevelofsurfing" ng-model="levelvalue" ng-change="setLevelText()">
{{levelvalue}}
</div>
<div id="leveldisplay">
</div>
{{testvariable}}
</ion-content>
</body>
</html>
JS:
angular.module('SnowBoard', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
.state('app.browse', {
url: "/browse",
views: {
'menuContent' :{
templateUrl: "templates/compute.html",
controller: 'ComputeCtrl'
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/playlists');
})
.controller('ComputeCtrl', function($scope, $ionicPopup, $timeout) {
$scope.data = {
levelvalue: 5,
level1wordDescription: "INTERMEDIATE+",
testvariable: "dummy"
}
$scope.$watch('data.levelvalue', function(newVal, oldVal) {
console.log('data.levelvalue is now '+newVal);
console.log('data.levelvalue is now '+data.levelvalue);
});
$scope.setLevelText = function(rangeValue) {
console.log('range value has changed to :'+$scope.data.levelvalue);
$scope.data.testvariable = $scope.data.levelvalue;
}
});
最佳答案
您可以使用其中任何一种,但在这种情况下我建议使用 ngChange。当您正在观看输入时,ngChange 通常是最佳选择。您应该最小化 $scope.$watch 表达式以提高性能,在这种情况下,它会复制 ngChange 已经处理的内容。移除 $watch。
您的问题出在 ng-model 中。您没有正确引用它,当您的模型实际上是 data.levelvalue
时,您有 levelvalue
。我还删除了 value="5"
属性,因为 ngModel 会处理这个问题并且它会妨碍您。
<input id="levelrange" type="range" min="0" max="10" name="userlevelofsurfing" ng-model="data.levelvalue" ng-change="setLevelText()">
关于javascript - $watch 或 ng-change,检测范围输入的 onchange 并根据值进行处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27077769/