简体   繁体   English

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

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

I have an input box which accepts the value for div width. 我有一个输入框,接受div宽度的值。 Using angular.js, How can you change div's width based on user input? 使用angular.js,如何根据用户输入更改div的宽度? I have implemented following code after referring this fiddle. 我在引用这个小提琴后实现了以下代码。 http://jsfiddle.net/311chaos/vUUf4/4/ http://jsfiddle.net/311chaos/vUUf4/4/

Markup: 标记:

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

controller.js 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


}

UPDATE My ultimate goal is to set width of that div. 更新我的最终目标是设置该div的宽度。 When I call inline CSS like following I achieve what I want. 当我调用内联CSS时,我会实现我想要的。

<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. 但如果div的数量很高,这并不总是有效的。 So, again question remains, how to do this via angular script? 所以,问题仍然存在,如何通过角度脚本来做到这一点?

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

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

You have an error in yor angular syntax. 您的角度语法有错误。 You Should use 你应该使用

ng-repeat="div in divs track by $index"

Also you should use attrs.$observe instead of $watch . 你也应该使用attrs.$observe而不是$watch

Working demo ( updated ): http://jsfiddle.net/nidzix/UKHyL/40/ 工作演示( 更新 ): http//jsfiddle.net/nidzix/UKHyL/40/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM