我有一个通过 AngularJS 中的指令实现的 jQuery slider ,它看起来像这样:
html
<div class="slider-container">
<div slider></div>
</div>
指令
myApp.directive('slider', function() {
return {
link: function(scope, elem, attrs) {
//slider settings, .noUiSlider is the method to initialize the slider
elem.noUiSlider({
range: [0,1440],
start: [690,750],
step: 30,
connect: true
});
}
};
});
这成功地实现了 slider ,但是在 elem(我的 slider )上调用方法 val() 只工作一次,就在实现 slider 时。我知道我需要使用某种形式的 $watch 但如果指令本身没有属性(然后通过 attrs 访问它)我不知道该怎么做,这不是。
基本上,我想观察 elem.val() 的变化,并在它们发生变化时打印出值 - 不确定如何去做。
注意:这段代码都在一个 ng-switch 中,我希望它不会让我的生活变得更糟。
谢谢你的帮助!
最佳答案
如果你只需要打印出值,你可以只处理它的change
事件:
myApp.directive('slider', function() {
return {
link: function(scope, elem, attrs) {
//slider settings, .noUiSlider is the method to initialize the slider
elem.noUiSlider({
range: [0,1440],
start: [690,750],
step: 30,
connect: true
}).change(function(){
//log your value here
});
}
};
});
当我们使用 Angular 时,我们通常需要将值绑定(bind)到模型的属性以符合 Angular 数据绑定(bind)机制。为此,您需要 ng-model
:
myApp.directive('slider', function() {
return {
require: '?ngModel',
link: function(scope, elem, attrs,ngModel) {
if (!ngModel) return;
//slider settings, .noUiSlider is the method to initialize the slider
elem.noUiSlider({
range: [0,1440],
start: [690,750],
step: 30,
connect: true
}).change(function(){
scope.$apply(function () {
// update the underlying model's property when slider changes
ngModel.$setViewValue(elem.val());
});
});
ngModel.$render = function() {
//update the slider when the underlying model changes.
elem.val(ngModel.$viewValue || []);
};
}
};
});
你的 html:
<div class="slider-container">
<div slider ng-model="sliderValue"></div>
</div>
这会将 slider 绑定(bind)到名为 sliderValue
的模型属性,您可以 $watch 此属性以获取更改。
关于javascript - 使用 AngularJS 观察 rangeSlider 值的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21654102/