角度-引导-滑块默认值/双向绑定

angular-bootstrap-slider default value / two-way binding

本文关键字:绑定 引导 角度 默认值      更新时间:2023-09-26

使用基于bootstrap-slider的角度引导滑块。这扩展了之前关于将值作为字符串获取的问题

我想将加载页面时显示的值设置为第一个值以外的任何其他值。

假设我希望显示"蓝色"而不是"红色"

如何设置将从另一个$scope返回的值。

或者,也许如何设置滑块的默认值?

我有一个有效的 Plunker 示例和下面的代码

脚本:

  $scope.colors = [{'id': 0,'label': 'red'},{'id': 1,'label': 'blue'},{'id': 2,'label': 'green'}];
  function getAttrs(collection, attr) {
    var attrArray = [];
    angular.forEach(collection, function(item) {
      attrArray.push(item[attr]);
    }) 
    return attrArray;
  }
$scope.colorTypeSlider = {
    ticks: getAttrs($scope.colors, 'id'), // [0,1,3]
    ticks_labels: getAttrs($scope.colors, 'label'), // ['red', 'blue','green']
    ticks_snap_bounds: 50,
};
$scope.selectedColor = '';
$scope.selectColor = function ($event,value,collection) {
  console.log('value is ' + value);
  $scope.selectedColor = collection[value];
};

.html:

 <slider ng-model="colors" 
        ticks="colorTypeSlider.ticks"
        ticks-labels="colorTypeSlider.ticks_labels"
        ticks-snap-bounds="colorTypeSlider.ticks_snap_bounds" 
        on-start-slide="selectColor($event,value,colorTypeSlider.ticks_labels)"></slider>
                <h6> value check is: {{selectedColor}} </h6>
我深入研究

了代码,并注意到 Bootstrap 的滑块(bootstrap-slider.js)使用属性"value"来设置其初始值。有关示例,请参阅此处。然后在它所在的角度引导滑块(slider.js)中,传入两个属性"ngModel"和"value"。然后,initSlider() 函数会做一些决策,并且我认为错误地弄乱了 ngModel 值。我发现如果我忽略"ngModel"而只依靠"value"属性,我可以默认滑块的初始值。

<span slider range="true" 
      precision="0" 
      scale="'logarithmic'" 
      ng-model="ngModel" 
      value="ngModel" 
      min="minValue" 
      step="1000" 
      max="maxValue"
      on-stop-slide="setValue()" 
      slider-tooltip="hide">
</span>

因此,在我上面的例子中(从我包含滑块的指令中),您可以看到我已经将指令 ngModel 设置为滑块 ng-model(我不再关心)和值(似乎有效)。 ng-model 是 angular-bootstrap-slider 所必需的,所以我不得不提供它,但它似乎没有坏处将值设置为相同的属性。