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

时间:2016-03-27 03:54:16

标签: javascript angularjs angularjs-directive

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

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

如下面的演示图片所示,当用户更新FORM元素时,相应的URL应为:https://lazyair.co/en/user/quick_search/index#?from=TOKYO&to=TAIPEI&depart=2016/06/03~2016/06/06&return=2016/06/08~2016/06/11&chart_type=column&depart_slider=10:00~24:00

inline

演示页: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

<ui-select.selectpicker{:theme => "select2", "ng-disabled" => "disabled", "ng-model" => "from", :name => "from", :theme => "select2", "ng-change"=>"updateDeparture(from)", :style => "width: 200px;", :required => "" }
  <ui-select-match{ "ng-cloak"=>"", :placeholder => t("from") } {{$select.selected.t_name}}  {{$select.selected.name}}</ui>
</ui>
<ui-select.selectpicker{"ng-disabled" => "disabled", "ng-model" => "to", :name => "to", :theme => "select2", "ng-change"=>"updateArrival(to)", :style => "width: 200px;", :required => ""}
  <ui-select-match.selectpicker{"ng-cloak"=>"", :placeholder => t("to")}  {{$select.selected.t_name}} {{$select.selected.name}}</ui>
  <ui-select-choices{:repeat => "node in arrivals | filter: $select.search" }
    <span ng-bind-html="node.t_name | highlight: $select.search"></span>
    <span ng-bind-html="node.name | highlight: $select.search"></span>
  </ui>
</ui>

url params在$rootScope.Scope#$digest周期

中被清除

inline

我在$locationChangeSuccess内放了一个断点,发现在$rootScope.Scope#$digest周期内清除了网址参数

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

双向绑定不适用于指令

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

inline

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',
        scope: false,
        link:function(scope, element, attr, ctrl){
            $(element).ionRangeSlider({
                    chartName: element.attr("chart-name"),
                    onChange: function(slider) {
                        scope[this.chartName] = slider.from+"~"+slider.to
                        scope.$apply();
                    }

            });
        }

    }
});

3 个答案:

答案 0 :(得分:3)

您可以创建服务以对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', ['$location', function($location) {
    this.bind = function(scope, getter, setter, urlParamName) {
        var unhookUrlUpdater = scope.$watch(getter, function(newValue) {
            $location.search(urlParamName, 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');

答案 1 :(得分:0)

你需要使用它并加载它你加载你的HTML ... 所以现在,你可以在你的配置中说出这样的话:

app.config(['$routeProvider', "$locationProvider",
    function ($routeProvider, $locationProvider) {

        /**
         * Redirect Using Code:
         * Internal: $location.path([path]);
         * External: $window.location.href([link]);
         */
        $routeProvider
        .when("/Taraz/:parent", {
                templateUrl: "/App/pages/taraz/index.html",
                controller: "TarazIndexController",
                resolve: {
                    urlId: ["$route",  function ($route) {
                        return Utility.parseUrlId($route.current.params.parent);//Parent HsbCod
                    }]
                }
            })

在这里我使用/ taraz / {code}来获取我的数据。你用// {你的数据} 将网址更改为所需的... 其次... 我解决了urlId ...它与服务非常相似,你将它传递给你的控制器,但请注意,如果你使用多个路由调用同一页面,你总是要解决它(空或填充)。

app.controller('TarazIndexController',
    ['$rootScope', '$scope', '$location', '$uibModal', 'urlId', 'FinYearService', 'SarfaslService', 'TarazService',
        function ($rootScope, $scope, $location, $uibModal, urlId, FinYearService, SarfaslService, TarazService) {

您可以使用location.path()发送数据,并更改路由。 location.path([路线])...

............................................... .................

还有其他方法可以使用ui-route,这种方式更复杂,功能更强大。它有点像ng-view,但因为我没有用它来自我,所以无法指导你。

答案 2 :(得分:0)

$ location有一个getter和一个setter。如果你看看

https://docs.angularjs.org/api/ng/service/ $位置

url([url]);
This method is getter / setter.

path([path]);
This method is getter / setter.

您也可以使用搜索或替换

this.$location.search(urlParamName, newValue);

replace();
If called, all changes to $location during the current $digest will replace the current history record, instead of adding a new one.

.when('/about/:name',{})

app.controller("aboutCtrl",function($scope,$routeParams,$route,$location){
    $scope.variable = "'From About Controller'";
    $scope.params = $routeParams.name;
    $scope.locationpath = $location.path();
    $scope.absolutelocationurl = $location.absUrl();
    $scope.locationurl = $location.url();    
    $scope.templateurl = $route.current.templateUrl;    
});