如何记住离子范围滑块位置$ ionicPopup

时间:2016-07-11 09:18:29

标签: ionic-framework angular-ngmodel ionicpopup

我有指令在页面上更改字体大小:

.directive('textSizeSlider', ['$document', function ($document) {
    return {
      restrict: 'E',
      template: '<div class="range"><i class="icon" ng-style="{ fontSize: min + unit }">A-</i><input type="range" min="{{ min }}" max="{{ max }}" step="{{ step || 0 }}" ng-model="textSize" value="{{ value }}" /><i class="icon" ng-style="{ fontSize: max + unit }">A+</i></div>',
      scope: {
        min: '@',
        max: '@',
        unit: '@',
        value: '@',
        step: '@'
      },
      link: function (scope, element, attr) {
        scope.textSize = scope.value;
        scope.$watch('textSize', function (size) {
            var x = document.getElementsByTagName("P");
            var i;
            for (i = 0; i < x.length; i++) {
            x[i].style.fontSize = size + scope.unit;
            }
        });
      }
    }
  }]);

在我的页面上按下按钮,单击打开弹出窗口以减小/增加字体大小。但每当我打开Popup范围滑块时,我的控制器中的值都有默认位置设置。如何保存Range的更改值?这是我在控制器中的功能:

  $scope.fontAdjust = function() {

    var alertPopup = $ionicPopup.alert({
    title: 'Font adjustment',
    template: '<text-size-slider min="10" max="18" unit="px" value="14" step="0"></text-size-slider>'
    })

   }

1 个答案:

答案 0 :(得分:1)

在控制器中添加了什么:

  1. 在控制器中有一个$scope.vm.fontSize变量,并在模板中使用它,如下所示

    template: '<text-size-slider min="10" max="18" unit="px" value="vm.fontSize" step="0"></text-size-slider>'
    

    您可以阅读Understanding Scopes以了解我使用vm.fontSize而非原始fontSize的原因。

  2. 在控制器中添加一个手表,以通知更改的值。这里改变的值可以保存在某处,例如在localStorage

    $scope.$watch('vm.fontSize', function (newValue, oldValue) {
      console.log(newValue);
      localStorage.fontSize = newValue;
    });
    
  3. 然后在你的指令中使用以下代码:

    return {
      restrict: 'E',
      template: '<div class="range"><i class="icon" ng-style="{ fontSize: min + unit }">A-</i><input type="range" min="{{ min }}" max="{{ max }}" step="{{ step || 0 }}" ng-model="value" /><i class="icon" ng-style="{ fontSize: max + unit }">A+</i></div>',
      scope: {
        min: '@',
        max: '@',
        unit: '@',
        value: '=',
        step: '@'
      },
      link: function (scope, element, attr) {
        scope.textSize = scope.value; // This is not required
        scope.$watch('value', function (size) {
          var x = document.getElementsByTagName("P");
          var i;
          for (i = 0; i < x.length; i++) {
            x[i].style.fontSize = size + scope.unit;
          }
        });
      }
    }
    

    指令改变了什么:

    1. value: '@'value: '='。这将在外部作用域中使用相同的引用,然后在指令作用域中创建本地引用。 Read More
    2. template属性中,添加ng-model="value"value(从外部范围)直接绑定到ng-model,并将value属性移除为{{ 1}}自动更新,不需要。
    3. 直接添加ng-model上的观看而不是value上的观看,这使得不需要。
    4. 加载控制器后,您可以阅读textSize并将其分配给localStorage.fontSize,并在其值更改时将其保存回$scope.vm.fontSize