我正在使用一些css html模板,它带有许多html组件,并且具有许多用于各种事物的数据属性.例如对于滑块它有类似的东西
<div class="slider slider-default"> <input type="text" data-slider class="slider-span" value="" data-slider-orientation="vertical" data-slider-min="0" data-slider-max="200" data-slider-value="{{ slider }}" data-slider-selection="after" data-slider-tooltip="hide"> </div>
在这里,我试图绑定价值
data-slider-value="{{ slider }}"
但它不起作用.变量’slider’在$scope中设置为:
$scope.slider = 80;
当我绑定它时,相同的值80显示为:
<h4>I have {{ slider }} cats</h4>
我也试过了
ng-attr-data-slider-value="{{ slider }}"
它没用.
更新
该指令有类似的东西
function slider() { return { restrict: 'A',link: function (scope,element) { element.slider(); } } };
解决方法
我玩了一段时间,并想出了一些选择.请参阅我的
Plunkr以查看它们的运行情况.
选项1:滑块更改时无需更新范围值
这将与您的问题中的HTML一起使用.以下是您应该将指令代码更改为的内容.
app.directive('slider',function slider() { return { restrict: 'A',link: function(scope,element,attrs) { attrs.$observe('sliderValue',function(newVal,oldVal) { element.slider('setValue',newVal); }); } } });
选项2:双向绑定到scope属性
如果在拖动滑块手柄时需要更新scope属性,则应将指令更改为以下内容:
app.directive('sliderBind',['$parse',function slider($parse) { return { restrict: 'A',attrs) { var val = $parse(attrs.sliderBind); scope.$watch(val,oldVal) { element.slider('setValue',newVal); }); // when the slider is changed,update the scope // property. // Note that this will only update it when you stop dragging. // If you need it to happen whilst the user is dragging the // handle,change it to "slide" instead of "slideStop" // (this is not as efficient so I left it up to you) element.on('slideStop',function(event) { // if expression is assignable if (val.assign) { val.assign(scope,event.value); scope.$digest(); } }); } } } ]);
此标记略有变化:
<div class="slider slider-default"> <input type="text" data-slider-bind="slider2" class="slider-span" value="" data-slider-orientation="vertical" data-slider-min="0" data-slider-max="200" data-slider-selection="after" data-slider-tooltip="hide" /> </div>
请注意使用data-slider-bind属性指定要绑定的scope属性,以及缺少data-slider-value属性.
希望这两个选项中的一个是你所追求的.