priyanka.sarkar priyanka.sarkar - 3 months ago 16
AngularJS Question

How to set the slider max value and how to make two way binding for the slider?

Following the example provided here , I have fit the slider as per the requirement

index.html



<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Rating</title>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css">
<script data-require="angular.js@1.4.0-beta.6" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>

<script src="test.js"></script>
</head>

<body ng-app="myApp">
<div ng-controller="testController">
<table>
<tr>
<td>Amount:</td>
<td><div slider ng-model="amount" style="width:200px;"></div></td>
<td><input type= "text" ng-model="amount" id="txtAmount"></td>
</tr>
</table>
</div>
</body>
</html>


test.js



var myApp = angular.module("myApp", []);
myApp.controller("testController", function($scope, $http){

$scope.amount = 1;

}); //end controller

myApp.directive('slider', function() {
return {
restrict: 'A',
scope: {
ngModel: '='
},
link: function(scope, elem, attrs) {

console.log(scope.ngModel);

return $(elem).slider({
range: "min",
animate: true,
value: scope.ngModel,
slide: function(event, ui) {
return scope.$apply(function(){
scope.ngModel = ui.value;
});
}
});
}
};
});


The problem is that

a) Max range cannot be set beyond 100. Say I want the min value as 1 and max as 1000. How to do that?

enter image description here

b) Two way binding is not happening. Say if I set the value of the "txtAmount " to 50, then the slider should point to that value(50)

enter image description here

Help needed.

Many thanks in advance

Answer
  1. Max range could be changed using max option you can see it in an example down below. If max field won't be specified in element it will set a maximum to 100.
  2. Two binding is working for Angular's elements because it's watching for changes, so you basically need to do the same for jQuery element

Code:

scope.$watch('ngModel', function(val) {
  $(elem).slider("value", val);
});

Full fiddle - http://jsfiddle.net/zv78jsz6/

Comments