5

I'm trying to use angular js bindings within a style element yet it doesn't seem to work. Is this a bug and is there a better way to do this?

<style ng-repeat="test in styles">
.test {
    background-color: {{ test.backgroundColor }};
    display: {{ test.display }};
    width: {{ test.width }};
    height: {{ test.height }};
    }
</style>

http://jsfiddle.net/cmsanche/PpyVn/

2
  • what is this supposed to accomplish? if you have more than one array item you will have 2 definitions for the same class name Commented Aug 9, 2012 at 21:06
  • The fiddle was just an example that angularjs wasn't parsing the style element. I could easily add something like .test_{{test.id}} to make each class name unique. I was working on a project where I needed to position a lot of images based on coordinates from a db. Commented Nov 21, 2012 at 18:45

2 Answers 2

7

I don't think Angular parses style elements. You probably want to use the ngStyle directive:

http://docs.angularjs.org/api/angular.module.ng.$compileProvider.directive.ngStyle

<!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/angular-1.0.0rc10.min.js"></script>
</head>
<body>
<div ng-init="styles=[{backgroundColor: 'red', width:'100px', height: '100px', display: 'block'}]">

<div ng-repeat="test in styles" ng-style="test">
.test {
    background-color: {{ test.backgroundColor }};
    display: {{ test.display }};
    width: {{ test.width }};
    height: {{ test.height }};
    }
</div>
</html>

Plunker (like jsFiddle, but more Angular-friendly) Demo

Sign up to request clarification or add additional context in comments.

1 Comment

I would like to find a way of doing this in a style tag in order to give a:hover some dynamic styles... Any ideas?
1

This now works in newer versions of Angular.

Here http://jsfiddle.net/PpyVn/4/ is the OPs fiddle with 1.0 replaced with 1.3.0-rc.3.

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.