How to set div width using ng-style

CssAngularjsNg Style

Css Problem Overview


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

Css Solutions


Solution 1 - Css

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.

Solution 2 - Css

ngStyle accepts a map:

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

Fiddle

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3049403View Question on Stackoverflow
Solution 1 - Cssmusically_utView Answer on Stackoverflow
Solution 2 - CssAlwaysALearnerView Answer on Stackoverflow