在angularjs中动态更改数组项

时间:2015-02-28 13:00:43

标签: javascript angularjs

我想以角度创建时间轴。在这个时间轴年中,鼠标滚轮事件发生变化。对于鼠标滚轮事件我使用hamster.js库。如何通过鼠标滚轮事件更改数组项? 这是我的代码:

angular.module('myApp', [])
.controller("Slider", function ($scope) {
var mouseWheel= document.getElementById('slider');

var hammer1 = Hamster(mouseWheel);
$scope.state = { zoom: 1, top: 0 };
$scope.dragY = 0;
 $scope._calc = function(state) {
    var years = [];
    var top = $scope.state.top;
    for (var i = -4000; i <= 2015; i += state.zoom) {
        var obj = {top: top, year: i};
        years.push(obj);
        top += 40;
    }
    return years;
}
$scope.years = $scope._calc($scope.state);
    hammer1.wheel(function(event, delta){
        if (delta > 0) {
          $scope.zoomOut();  // this function not working
        } else if (delta < 0) {
                $scope.zoomIn();   
        }
    });
$scope.zoomOut= function () {
    $scope.state.zoom += 10;
    $scope.years = $scope._calc($scope.state);
};

})

2 个答案:

答案 0 :(得分:1)

我敢打赌,你的仓鼠回调不会触发摘要。尝试使用$ scope。$ apply():

hammer1.wheel(function(event, delta){
    $scope.$apply(function () {
        if (delta > 0) {
            $scope.zoomOut();  // this function not working
        } else if (delta < 0) {
            $scope.zoomIn();   
        }
    }
});

答案 1 :(得分:0)

您必须致电$scope.$digest();$scope.$apply();,以便有角度知道它应该重新报名:

hammer1.wheel(function(event, delta){
        if (delta > 0) {
          $scope.zoomOut();  // this function not working
        } else if (delta < 0) {
          $scope.zoomIn();   
        }
        $scope.$digest();
    });

另见digest and apply explained in detail