Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set div width using ng-style

I am trying to set the div width dynamically using ng-style but it is not applying the style. Here is the code:

<div style="width: 100%;" id="container_fform" ng-controller="custController">
    <div style="width: 250px;overflow: scroll;">
        <div ng-style="myStyle">&nbsp;</div>
    </div>
</div>

Controller:

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

var custController = MyApp.controller('custController', function ($scope) {
    $scope.myStyle="width:'900px';background:red";

});

What am I missing?

Fiddle link: Fiddle

like image 782
user3049403 Avatar asked Nov 29 '13 13:11

user3049403


People also ask

What is NgClass and NgStyle?

The NgClass and NgStyle directives are used to apply style to the HTML element conditionally. The NgClass allows you to apply whole class based on condition whereas NgStyle gives you more flexibility to set individual properties.

What is the use of NG style directive?

The NgStyle directive lets you set a given DOM elements style properties. This sets the background color of the div to green. The above code uses the ternary operator to set the background color to green if the persons country is the UK else red.


2 Answers

The syntax of ng-style is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:

<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>

And then in your controller:

$scope.width = '900px';
$scope.bgColor = 'red';

This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.

like image 85
musically_ut Avatar answered Oct 21 '22 03:10

musically_ut


ngStyle accepts a map:

$scope.myStyle = {
    "width" : "900px",
    "background" : "red"
};

Fiddle

like image 25
AlwaysALearner Avatar answered Oct 21 '22 04:10

AlwaysALearner