Sujit Kulkarni Sujit Kulkarni - 1 year ago 190
HTML Question

Angular.js: How to change div width based on user input

I have an input box which accepts the value for div width.
Using angular.js, How can you change div's width based on user input?
I have implemented following code after referring this fiddle.


<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>


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;


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

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

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


My ultimate goal is to set width of that div. When I call inline CSS like following I achieve what I want.

<div get-width row-height="{{cols}}" ng-repeat="div in divs" style="width:{{cols}}px">{{$index+1}} aaaaaa</div>

But this wouldn't be always efficient if number of divs goes high. So, again question remains, how to do this via angular script?

Answer Source

Use ng-style="{width: cols + 'px'}", instead of style.

link to the docs:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download