0

I would like to have an img with a random css rotation. I managed to achieve this, but when you move your mouse over the leaftlet map, the img is always spinning around:

http://jsfiddle.net/J03rgPf/mzwwfav4/3/

How can I set a random css only once, so that the getRandRot function is not called again and again?

<body ng-controller="DemoController">
 <leaflet center="center"></leaflet>
 <div class="{{getRandRot()}}">
     <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/0a/Surfers_at_Mavericks.jpg/320px-Surfers_at_Mavericks.jpg" />
 </div>  
</body>

Angular JS Code:

var app = angular.module('demoapp',['leaflet-directive']);

app.controller('DemoController', [ '$scope', 'leafletData', function($scope, leafletData) {
    angular.extend($scope, {
        center: {
            lat: 51.505,
            lng: -0.09,
            zoom: 5
        }
    })

    $scope.getRandRot = function(){
        var rotations = [ "rotate-10", "rotate-5", "rotate5", "rotate10" ];
        var rand = Math.floor(Math.random() * rotations.length);
        return rotations[rand];  
      }
}]);

CSS

.angular-leaflet-map {
    width: 100%;
    height: 280px;
}

.rotate-10{
    -moz-transform: rotate(-10deg);
    -ms-transform: rotate(-10deg);
    -o-transform: rotate(-10deg);
    -webkit-transform: rotate(-10deg);
}
.rotate-5{
    -moz-transform: rotate(5deg);
    -ms-transform: rotate(5deg);
    -o-transform: rotate(5deg);
    -webkit-transform: rotate(5deg);
}
.rotate5{
    -moz-transform: rotate(5deg);
    -ms-transform: rotate(5deg);
    -o-transform: rotate(5deg);
    -webkit-transform: rotate(5deg);
}
.rotate10{
    -moz-transform: rotate(10deg);
    -ms-transform: rotate(10deg);
    -o-transform: rotate(10deg);
    -webkit-transform: rotate(10deg);
}
4

1 回答 1

1

也许将对 getRandRot 的调用响应分配给控制器中的值?

通过使用class={{ getRandRot() }},您正在创建一个绑定getRandRot,将在每个摘要阶段调用该绑定

这可以解决问题:

HTML

 <body ng-controller="DemoController">
   <leaflet center="center"></leaflet>
   <div ng-class="randRot">
     <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/0a/Surfers_at_Mavericks.jpg/320px-Surfers_at_Mavericks.jpg" />
   </div>  
</body>

JS

var app = angular.module('demoapp',['leaflet-directive']);

app.controller('DemoController', [ '$scope', 'leafletData', function($scope, leafletData) {
    angular.extend($scope, {
        center: {
            lat: 51.505,
            lng: -0.09,
            zoom: 5
        }
    })

    getRandRot = function(){
        var rotations = [ "rotate-10", "rotate-5", "rotate5", "rotate10" ];
        var rand = Math.floor(Math.random() * rotations.length);
        return rotations[rand];  
      }

    $scope.randRot = getRandRot();
}]);

顺便说一句,ng-class 是使用 angular 在元素上动态设置类的首选方法。

希望这可以帮助。

于 2015-01-07T16:53:20.013 回答