How to set div width using ng style

I am trying to set the width of a div dynamically using ng-style , but not applying a 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?

Script Link: Fiddle

+75
angularjs css ng-style
Nov 29 '13 at 13:46
source share
2 answers

The ng-style syntax is not quite like that. It accepts a dictionary of keys (attribute names) and values ​​(the value that they should take, an empty string disables them), and not just a string. I think you want 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 the template and the controller: the controller stores semantic values, and the template matches them with the correct attribute name.

+131
Nov 29 '13 at 13:50
source share

ngStyle accepts the card:

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

Fiddle

+34
Nov 29 '13 at 13:48 on
source share



All Articles