I am new to AngularJS/Ionic and I am trying to detect the change of value of an input type="range", and to do things in js depending on this value.
But I am not sure how to detect it : $watch or ng-change ?
Here's the code : 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;
}
});
You could use either, though I recommend ngChange in this case. When you are watching an input, ngChange is usually the best choice. You should minimize $scope.$watch expressions for performance, and in this case it would duplicate what ngChange already handles. Remove the $watch.
Your problem here is in the ng-model. You did not reference it correctly, you have levelvalue
when your model is actually data.levelvalue
. Also I removed the value="5"
attribute, as ngModel takes care of this and it was getting in the way.
<input id="levelrange" type="range" min="0" max="10" name="userlevelofsurfing" ng-model="data.levelvalue" ng-change="setLevelText()">