简体   繁体   English

使用ng-style在css中动态转换

[英]Dynamically transform in css using ng-style

I could not get transform to work when it's inside ng-style . 当它在ng-style时,我无法transform为工作。

<!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="angular.js@1.2.x" 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 链接: http//plnkr.co/edit/txSzAKxLDq48LVitntro?p=preview

If I change the input number the top div should change and spin at the same time. 如果我改变input数字,顶部div应该改变并同时旋转 It should look like the word Test above it when it has value of 3. 当它的值为3时,它应该看起来像上面的单词Test

So how to get transform to work in this case? 因此,如何让transform在这种情况下工作?

Thanks. 谢谢。

You can't use brace binding inside a JS string inside an attribute. 您不能在属性内的JS字符串中使用大括号绑定。 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: 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 更新了Plunker

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM