Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically transform in css using ng-style

I could not get transform to work when it's inside ng-style.

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="http://code.angularjs.org/1.2.13/angular.js" data-semver="1.2.13"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <div style="transform: rotate(3deg);-webkit-transform: rotate(3deg);-ms-transform: rotate(3deg)">Test</div>
    <div ng-style="{"transform": "rotate({{number}}deg)", "-webkit-transform": "rotate({{number}}deg)", "-ms-transform": "rotate({{number}}deg)"}">{{number}}</div>
    <input type="number" ng-model="number" value=1>
  </body>

</html>

Link: http://plnkr.co/edit/txSzAKxLDq48LVitntro?p=preview

If I change the input number the top div should change and spin at the same time. It should look like the word Test above it when it has value of 3.

So how to get transform to work in this case?

Thanks.

like image 914
HP. Avatar asked Feb 28 '14 09:02

HP.


People also ask

How do I add dynamic CSS in angular 6?

create a new component and create a service to load dynamic css variables from API. Add style tag in template file and use variable values for properties. Load this template on all pages or on main template. On app build style will be moved to head tag.

Can we use NgClass and ngStyle together?

Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.


1 Answers

You can't use brace binding inside a JS string inside an attribute. You can append the variable onto the string instead:

<div ng-style="{'transform': 'rotate('+number+'deg)', '-webkit-transform': 'rotate('+number+'deg)', '-ms-transform': 'rotate('+number+'deg)'}">{{number}}</div>

Also, I replaced your double-quotes with singles.

However, you might consider adding a function to your controller to return the appropriate style:

Controller:

// Create a variable to store the transform value
$scope.transform = "rotate(0deg)";
// When the number changes, update the transform string
$scope.$watch("number", function(val) {
    $scope.transform = "rotate("+val+"deg)";
});

HTML:

<!-- We can now use the same value for all vendor prefixes -->
<div ng-style="{'transform': transform, '-webkit-transform': transform, '-ms-transform': transform }">{{number}}</div>

Updated Plunker

like image 159
CodingIntrigue Avatar answered Oct 05 '22 10:10

CodingIntrigue