绑定Range输入以修改样式?

时间:2015-04-09 00:31:10

标签: javascript angularjs

我想要一个控制几个div的高度和宽度的滑块,但是,我似乎无法让它们正确绑定。

<div ng-controller="SizeCtrl">
    <input type="range" min="100" max="200" ng-model="sliderval" />
    <div class="box" ng-style="height:sliderval; width:sliderval"> Box 1</div>
    <div class="box" ng-style="height:sliderval; width:sliderval"> Box 2</div>
    <div class="box" ng-style="height:sliderval; width:sliderval"> Box 3</div>
    <div class="box" ng-style="height:sliderval; width:sliderval"> Box 4</div>
    <div class="box" ng-style="height:sliderval; width:sliderval"> Box 5</div>
</div>

https://jsfiddle.net/nopctoday/dnvwbywv/3/

3 个答案:

答案 0 :(得分:3)

尝试我的修复: https://jsfiddle.net/dnvwbywv/4/

我不得不在代码中添加ng-app,也改变了样式的约束方式。

<div class="box" style="height:{{sliderval}}px; width:{{sliderval}}px"> Box 1</div>

答案 1 :(得分:0)

您可以像这样使用ng-style

&#13;
&#13;
var myApp = angular.module('myApp', []);

myApp.controller('SizeCtrl', function($scope) {
  $scope.$watch('sliderval', function() {
    $scope.myStyle.height = $scope.sliderval + 'px',
    $scope.myStyle.width =  $scope.sliderval + 'px'
  });
  
  $scope.sliderval = 100;
  $scope.myStyle = {};  
});
&#13;
.box {
  height: 100px;
  width: 100px;
  border: red 2px solid;
  margin: 1em;
  display: inline-block;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app="myApp" ng-controller="SizeCtrl">
  <input type="range" min="100" max="200" ng-model="sliderval" />{{sliderval}}
  <div class="box" ng-style="myStyle">Box 1</div>
  <div class="box" ng-style="myStyle">Box 2</div>
  <div class="box" ng-style="myStyle">Box 3</div>
  <div class="box" ng-style="myStyle">Box 4</div>
  <div class="box" ng-style="myStyle">Box 5</div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您也可以ng-style使用<div ng-app="myApp"> <div ng-controller="SizeCtrl"> <input type="range" min="100" max="200" ng-model="sliderval" /> <div class="box" ng-style="{'height':sliderval+'px', 'width':sliderval+'px'}"> Box 1</div> <div class="box" ng-style="{'height':sliderval+'px', 'width':sliderval+'px'}"> Box 2</div> <div class="box" ng-style="{'height':sliderval+'px', 'width':sliderval+'px'}"> Box 3</div> <div class="box" ng-style="{'height':sliderval+'px', 'width':sliderval+'px'}"> Box 4</div> <div class="box" ng-style="{'height':sliderval+'px', 'width':sliderval+'px'}"> Box 5</div> </div> </div>

HTML:

<div ng-app="myApp">

这里的变化是:

  • 添加ng-style
  • ng-style="{'height':sliderval+'px', 'width':sliderval+'px'}"更改为var myApp = angular.module('myApp', []); myApp.controller('SizeCtrl', function ($scope, $element) { $scope.sliderval = 100; });

JavaScript的:

sliderval

这里的变化是:

  • 初始化onLoad变量
  • 将脚本选项从No wrap - in <head>更改为{{1}}