带AngularJS的文本大小滑块

时间:2015-08-19 04:33:02

标签: angularjs fonts scope font-size

我试图更改精确文本的字体和字体大小,我更改了字体部分并更改了大小,但却改为两种不同的文本。如何将这两个功能应用于文本。

这是我的HTML

<div ng-controller="StylesCtrl">
                    <select ng-model="font" ng-options="font as font.label for font in fonts" ng-change="change(font)"></select>
                    <h3><font face="{{selectedFont}}">Text Is</font></h3>
                </div>
                <text-size-slider min="12" max="24" unit="px" value="18"></text-size-slider>
                <div>Font Size Slider</div>

这是我的脚本文件

(function () {
angular.module('appBuilderApp').controller("StylesCtrl", function ($scope) {
    $scope.fonts = [
       {
          value: 'Arial',
          label: 'Arial'
        },
        {
          value: 'Tahoma',
          label: 'Tahoma'
        }
    ];
    $scope.selectedFont = '';
    $scope.change = function (option) {
       $scope.selectedFont = option.value;
    }
});

angular.module('appBuilderApp').directive('textSizeSlider', ['$document', function ($document) {
    return {
      restrict: 'E',
      template: '<div class="text-size-slider"><span class="small-letter" ng-style="{ fontSize: min + unit }">A</span> <input type="range" min="{{ min }}" max="{{ max }}" step="{{ step || 0 }}" ng-model="textSize" class="slider" value="{{ value }}" /> <span class="big-letter" ng-style="{ fontSize: max + unit }">A</span></div>',
      scope: {
        min: '@',
        max: '@',
        unit: '@',
        value: '@',
        step: '@'
      },
      link: function (scope, element, attr) {
        scope.textSize = scope.value;
        scope.$watch('textSize', function (size) {
          $document[0].body.style.fontSize = size + scope.unit;
        });
      }
    }
  }]);
})();

请帮我将这两个功能应用到一个文本中。

1 个答案:

答案 0 :(得分:5)

为了实现这一点,我稍微简化了代码,并尝试更多地使用内置的Angular指令以及一些HTML5功能。这是您的代码的工作版本。

HTML:

<div ng-controller="StylesCtrl">
    <select ng-options="font for font in fonts" ng-model="text.font"></select>
    <h3 ng-style="{'font-family': text.font, 'font-size': text.size + 'px'}">Text Is</h3>
    <input min="12" max="24" ng-model="text.size" type="range">
    <div>Font Size Slider</div>
</div>

JS:

(function () {
    angular.module("appBuilerApp", [])
    .controller("StylesCtrl", function ($scope) {
        $scope.fonts = [
            "Arial",
            "Tahoma"
        ];

        $scope.text = {
            font: "Arial",
            size: 18
        };
    });
})()

这里的主要变化是我使用范围输入而不是滑块的自定义指令。如果您需要IE9及更低版本的支持,可以使用polyfill来帮助您自动生成范围输入。

其次,我使用ngStyle指令而不是手动更改样式。这是在转移到Angular时所需的典型思维模式更改 - 在事件侦听器之前思考数据绑定。

最后,我更多地使用了ngModel指令,它将DOM中不同输入的值绑定到数据变量。根据经验,您应该始终尝试使用ngModel绑定输入值,然后在其他地方使用其他指令,而不是使用ngChange来监听改变事件。