Angular.js:如何根据用户输入更改div宽度

Suj*_*rni 4 html javascript css angularjs

我有一个输入框,接受div宽度的值.使用angular.js,如何根据用户输入更改div的宽度?我在引用这个小提琴后实现了以下代码.http://jsfiddle.net/311chaos/vUUf4/4/

标记:

 <input type="text" id="gcols" placeholder="Number of Columns" ng-model="cols" ng-change="flush()"/>

<div getWidth rowHeight=cols ng-repeat="div in divs">{{$index+1}} aaaaaa</div>
Run Code Online (Sandbox Code Playgroud)

controller.js

var grid = angular.module('gridApp', []);

grid.controller('control', ['$scope', function ($scope) {

    /* code for repeating divs based on input*/
    $scope.divs = new Array();
    $scope.create=function(){ //function invoked on button's ng-click
            var a = $scope.cols;
            for(i=0;i<a;i++)
            {
                $scope.divs.push(a);
            }
            alert($scope.divs);
        };


}]);

grid.directive('getWidth', function () {
    return {
        restrict: "A",
        scope: {
            "rowHeight": '='
        },
        link: function (scope, element) {

            scope.$watch("rowHeight", function (value) {
                console.log(scope.rowHeight);
                $(element).css('width', scope.rowHeight + "px");
            }, false);
        }
    }
});

function appCtrl($scope) {
    $scope.cols = 150;   //just using same input value to check if working


}
Run Code Online (Sandbox Code Playgroud)

更新 我的最终目标是设置该div的宽度.当我调用内联CSS时,我会实现我想要的.

<div get-width row-height="{{cols}}" ng-repeat="div in divs" style="width:{{cols}}px">{{$index+1}} aaaaaa</div>
Run Code Online (Sandbox Code Playgroud)

但如果div的数量很高,这并不总是有效的.所以,问题仍然存在,如何通过角度脚本来做到这一点?

Jon*_*now 31

使用ng-style="{width: cols + 'px'}",而不是样式.

链接到文档:http://docs.angularjs.org/api/ng.directive:ngStyle

  • 编写内联样式通常不是一种好的做法,但在这种情况下,这是调整元素大小的唯一方法.至于风格的AFAIK,它仍然添加了style ="",但是您可以将范围变量映射到它,这样您就可以执行类似ng-style ="styles"的操作,并在范围中添加样式,如:$ scope.styles = {width :某事+'px'} (4认同)