AngularJS中滑块的双向数据绑定

时间:2015-09-30 11:13:57

标签: javascript jquery angularjs

我有一个用例,我需要使用slider-directive来更新配置&通过控制器动态建模值。为此,我试图创建一个双向数据绑定。但是,我无法找到在指令中创建双向数据绑定的正确方法。 以下是代码。目前,滑块触发器上的幻灯片事件指示更新&#scope; model.model'。虽然它没有响应&#; scope.config'的控制器更新。或者&#;; scope.model':

.directive("slider", function() {
return {
    restrict: 'A',
    scope: {
        config: "=config",
        model: "=model",
        trigger: '=trigger'
    },
    link: function(scope, elem, attrs) {

     //Data Binding to be done here using $watch for scope.model

        $(elem).slider({
            range: "min",
            min: scope.config.min,
            max: scope.config.max,
            value: scope.model,
            step: scope.config.step,
            slide: function(event, ui) {
                scope.$apply(function() {
                    scope.model = ui.value;
                });
                console.log(scope.model);
                scope.$apply(scope.trigger);
            }
            });
        }
    }
});

请帮帮我。我已经完成了所有可用的答案,但无法找到合适的答案

2 个答案:

答案 0 :(得分:1)

将您的指令基于ngModelController。通过这种方式,您可以使用ngModel功能绑定所有内容,并使用ngChange运行回调,而无需$watchplunkr):

app.directive("slider", function() {
  return {
    restrict: 'A',
    scope: {
      config: "=config"
    },
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModel) {
      var init = false;
      var $slider = $(elem);

      ngModel.$render = function() {
        if (!init) {
          $slider.slider({
            range: "min",
            min: scope.config.min,
            max: scope.config.max,
            step: scope.config.step,
            slide: function(event, ui) {
              scope.$apply(function() {
                ngModel.$setViewValue(ui.value);
              });
            }
          });

          init = true;
        }

        $slider.slider('value', parseInt(ngModel.$viewValue, 10));
      }

    }
  }
});

用法:

  <div id="km-slider" class="slider" slider="" config="milesSliderConfig" 
  ng-change="filterCars(sliderRanges.kms)"
  ng-model="sliderRanges.kms"></div>

答案 1 :(得分:0)

我已经通过使用$ watch

找到了解决方案
//watch the Model to set slider when val in Model var changes
scope.$watch('model', function(newVal, oldVal){
   //check when Model is not initialized
   if (newVal !== undefined){
      elem.slider("value", parseInt(newVal,10));
       }
});