javascript - 使用 AngularJS 观察 rangeSlider 值的变化

标签 javascript jquery angularjs uislider

我有一个通过 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/

相关文章:

javascript - 调用继承的方法 javascript 原型(prototype)

javascript - jquery如何在运行时获取数据?

javascript - 那么函数没有定义

javascript - 在 .splice() 之后重置 Angular 函数中的数组副本

javascript - 从另一个 div 获取值,减去,并使用 jQuery 填充另一个 div

javascript - Angular 自定义过滤器在服务器上不起作用

javascript - 更新 DOM 与在 Angular 中重新渲染 View

javascript - 如何发送 JSON 数据而不是将其记录到控制台

javascript - 使用数据属性过滤选择框(使用第三方JS过滤代码)

javascript - 我怎样才能保持这个表头固定?