javascript – 使用URL双向绑定获取params和Form值(选项和滑块)

前端之家收集整理的这篇文章主要介绍了javascript – 使用URL双向绑定获取params和Form值(选项和滑块)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

目前,我可以通过$location.$$搜索获取GET参数.

但是,我仍然不知道如何在以下情况下对URL和FORM进行双向绑定.

如下面的演示图片,当用户更新FORM元素时,相应的URL应为:https://lazyair.co/en/user/quick_search/index#?from = TOKYO& to = TAIPEI& undepart = 2016/06/03/03 〜2016/06/06&安培;回报率= 2016/06/08〜2016/06/11安培; CHART_TYPE =柱&安培; depart_slider = 10:00〜24:00

演示页面https://lazyair.co/en/user/quick_search/index

Sliderbar指令JavaScript代码

  'use strict';

  quick_search_app.directive('ionslider',function($timeout){

      var get_hour_minute,getHHMMformat,isDepartureAtInInterval;

      get_hour_minute = function(value) {
        var hours,minutes;
        hours = Math.floor(value / 60);
        minutes = value - (hours * 60);
        if (hours.length === 1) {
          hours = '0' + hours;
        }
        if (minutes.length === 1) {
          minutes = '0' + minutes;
        }
        return [hours,minutes];
      };

      getHHMMformat = function(values) {
        var hours,minutes;

              hours = values[0].toString();
              minutes = values[1].toString();
              if (hours.length === 1) {
                hours = '0' + hours;
              }
              if (minutes.length === 1) {
                minutes = '0' + minutes;
              }
              return hours + ':' + minutes;
            }
      isDepartureAtInInterval = function(departure_at,slider){
          var t = new Date(Date.parse(departure_at))
          var HHMM_in_minutes = t.getUTCHours()*60 + t.getMinutes();
          return slider.from <= HHMM_in_minutes && slider.to >= HHMM_in_minutes;
      }
      var updateFlighSeries = function(slider,flight_series) {
        $.each(flight_series,function() {
            var current_series = this;
            angular.forEach(current_series.data,function(value,key) {
                  if(isDepartureAtInInterval(value.departure_at,slider)){
                      this.visible = true ;
                  }else{
                      this.visible = false ;
                  }
              },current_series);
        });
      }
      return{
          restrict:'AE',scope: false,controller: 'quick_search_ctrl',link:function(scope,element,attr,ctrl){
              $(element).ionRangeSlider({
                      hide_min_max: true,keyboard: true,min: 0,max: 1440,from: 0,to: 1440,type: 'double',step: 30,prefix: "",chartConfig: element.attr("chart-config"),grid: true,prettify: function (value) {
                        return getHHMMformat(get_hour_minute(value));
                      },onChange: function(slider) {
                          var _this = this;
                          updateFlighSeries(slider,scope[_this.chartConfig].series)
                          angular.forEach(scope.chart_names,function(chart_cfg_name){
                                scope.$apply(function () {
                                  scope.lowestFlights[chart_cfg_name]  = angular.copy(scope.filterLowestPrice(scope[chart_cfg_name]))
                                  console.log(scope.lowestFlights[chart_cfg_name])
                                });
                          },scope)
                      }
              });
          }
      }
  });

HTML

required => "" }
  required => ""}
  

url params在$rootScope.Scope#$digest循环中清除

我在$locationChangeSuccess中放了一个断点,发现在$rootScope.Scope#$digest cycle中清除了url params

app.run(function ($rootScope) {
    $rootScope.$on('$locationChangeSuccess',function () {
        debugger
        console.log('$locationChangeSuccess changed!',new Date());
    });
});

双向绑定不适用于指令

双向绑定不适用于指令,
实际上,双向绑定适用于View,但不适用于URL参数

DEMO第http://133.130.101.114:3000/en/user/quick_search/index

controller(注册departChartName并用输入框显示其值)

  $scope.departChartName = "yoyoyo"
  urlBinder.bind($scope,"departChartName","dpnAME")

滑块指令

app.directive('ionslider',function($timeout){
    return{
        restrict:'AE',ctrl){
            $(element).ionRangeSlider({
                    chartName: element.attr("chart-name"),onChange: function(slider) {
                        scope[this.chartName] = slider.from+"~"+slider.to
                        scope.$apply();
                    }

            });
        }

    }
});
最佳答案
您可以创建服务以对URL参数进行双向绑定:

angular.module('app').service('urlBinder',['$location',function($location) {
    this.bind = function(
        scope,// angular scope
        varName,// string : name of the variable on the scope to bind to
        urlParamName   // string : name of the url parameter to bind to
        ) {

        // when scope variable changes,update the URL
        var unhookUrlUpdater = scope.$watch(varName,function(newValue) {
            $location.search(urlParamName,newValue);
        });

        // when the URL changes,update the scope variable
        var unhookScopeUpdater = scope.$on('$locationChangeSuccess',function() {
            var value = $location.search()[urlParamName];

            if (!angular.equals(scope[varName],value)) {
                scope[varName] = value;
            }
        });

        // return a function that can be called to remove the bindings
        return function() {
            unhookUrlUpdater();
            unhookScopeUpdater();
        };
    };
}]);

如果你绑定的东西不在范围内,你也可以用getter / setter函数而不是varName做同样的事情:

angular.module('app').service('urlBinder',function($location) {
    this.bind = function(scope,getter,setter,urlParamName) {
        var unhookUrlUpdater = scope.$watch(getter,newValue);
        });

        var unhookScopeUpdater = scope.$on('$locationChangeSuccess',function() {
            var value = $location.search()[urlParamName];

            if (!angular.equals(getter(),value)) {
                setter(value);
            }
        });

        return function() {
            unhookUrlUpdater();
            unhookScopeUpdater();
        };
    };
}]);

在你的控制器中:

var someVariable;
urlBinder.bind(
    $scope,function() { return someVariable; },function(value) { someVariable = value; },'url-name');
原文链接:https://www.f2er.com/js/428995.html

猜你在找的JavaScript相关文章