1

我想基于它们的数组索引使用ng样式有条件地设置div元素的背景位置。每个div都是使用ng repeat生成的。AngularJS - TypeError:v2。[xxxx]不是函数

在我的html页面,我有下面的代码片段:

<div style="position:absolute; z-index:1; width:100px; height:100px" ng-style="navigationStyleToilet(o)" ng-repeat="o in arr"></div> 

在我controller.js,我有下面的代码片段:

$scope.navigationStyleToilet = []; 
    $scope.arr = []; 
    // get data from service.js 
    var categoryInfo = NavigationService.fnGetCategoryInfo(strCategoryName); 

    for (i = 0; i < categoryInfo.length; i++) 
    { 
     $scope.arr.push(i); 
     var targetImageX = categoryInfo[i].X; 
     var targetImageY = categoryInfo[i].Y; 
     $scope.navigationStyleToilet[i] = { 
      "background-position": targetImageX + " " + targetImageY 
     } 
    } 

不幸的是,它给我的错误说“TypeError:v2.navigationStyleToilet不是一个函数”。

我已经尝试了几个不同的事情,但是我不能有条件地使用ng-style基于它们的数组索引设置div元素的背景位置。有没有人知道我可以做这项工作的方式?谢谢。

+0

你有$ scope.navigationStyleToilet内的值吗? – Sajeetharan

+0

值?基本上,$ scope.navigationStyleToilet是一个ng格式的div。 div会重复生成,我想根据数组索引为每个div有条件地设置不同的背景位置。顺便说一句,我已经更新了我的问题,因为我忘了提及我已经声明并实例化$ scope.navigationStyleToilet = []; – Antoni

+0

下面的答案是根据更新的问题! –

回答

0

如果你想从数组中获取元素,你应该在数组中使用索引器。所以,你在NG-风格索引应该是

ng-style="navigationStyleToilet[o]" 

您的代码ng-style="navigationStyleToilet(o)"会认为它的功能并以这种方式调用。所以,你应该使用索引器而不是调用函数。 确保o应将索引值从数组中获取数据。

如果你想获得ng-repeat产生的索引,你可以使用$ index。所以,你的代码可能是这样的:

ng-style="navigationStyleToilet[$index]" 
0

首先,你不需要为此分离功能。

$scope.categoryInfo 

<div style="position:absolute; z-index:1; width:100px; height:100px" ng-style="{'background-position': o.X + 'px ' + o.Y +'px' }" ng-repeat="o in categoryInfo">{{o}}</div> 

这里解决: https://plnkr.co/edit/Nh0Kp0zI77JIxcApTYSQ?p=preview

您可能忽略像素或%

您可以通过它改变穿上categoryInfo NG-重复在“背景位置”属性中所要求的值中

但正如你所看到的(通过检查元素)在上述plunkr都在div有“背景,地位”,那么还他们overlapsing:

所以你可能会寻找这样的事情:

ng-style="{'left': o.X + 'px ', 'top': o.Y +'px' }" ng-repeat="o in categoryInfo" 

请看这里:https://plnkr.co/edit/g0h7IsG1kSkNQmSLBDWY?p=preview

希望这会有所帮助。 :)