AngularJS - jQueryUI slider values ​​for models

I have the following directive:

directive('yearSlider', function(Filter) { return { restrict: 'E', // must be an element transclude: false, // don't preserve content controller: function($scope) { $scope.$watch('yearMin + yearMax', function(newVal, oldVal) { if(newVal === oldVal) return; // skip initialization $("#year-slider").slider("option", "min", parseInt($scope.yearMin)); $("#year-slider").slider("option", "max", parseInt($scope.yearMax)); $("#year-slider").slider("value", $("#year-slider").slider("value")); }); }, link: function postLink($scope, $element) { $element.slider({ range: true, min: 1900, max: new Date().getFullYear(), values: [ 1900, new Date().getFullYear() ], slide: function(event, ui) { $scope.yearFrom = ui.values[0]; $scope.yearTo = ui.values[1]; $scope.$apply(); }, change: function(event, ui) { $scope.yearFrom = ui.values[0]; $scope.yearTo = ui.values[1]; Filter.apply($scope); } }); }, template: '<div id="year-slider"></div>', replace: true } }). 

This directive is used in the view and displays the slider correctly.

I assign both slider values ​​to the two yearFrom and yearTo models to get the range of years indicated by the slider. In some cases, I need to change the min / max values ​​of the slider and what I do in the controller above.

The problem is that I am observing both yearMin and yearMax , and these two models change sequentially, which causes the controller and change from $element.slider executed twice.

What I'm trying to achieve is to do it once, but the fact that I have two models makes it logically impossible.

+4
source share
1 answer

I figured this out when writing the question, I just changed my model to:

 $scope.years = { min: data.yearMin, max: data.yearMax } 

And changed my $ watch to:

 $scope.$watch('years', function(newVal, oldVal) { if(newVal === oldVal) return; // skip initialization $("#year-slider").slider("option", "min", parseInt($scope.years.min)); $("#year-slider").slider("option", "max", parseInt($scope.years.max)); $("#year-slider").slider("value", $("#year-slider").slider("value")); }); 

Putting the jQuery slider aside, this is a common problem I encountered with AngularJS, especially having many models firing multiple events for observers, while I needed them to fire once. I believe that grouping them in a similar way (if applicable) will solve this problem.

+6
source

Source: https://habr.com/ru/post/1444995/


All Articles