【问题标题】:AngularJS - TypeError: v2.[xxxx] is not a functionAngularJS - TypeError: v2.[xxxx] 不是函数
【发布时间】:2017-05-17 01:53:59
【问题描述】:

我正在尝试使用 ng-style 根据其数组索引有条件地设置 div 元素的背景位置。每个 div 都是使用 ng repeat 生成的。

在我的html页面中,我有以下代码sn-p:

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

在我的 controller.js 中,我有以下代码 sn-p:

  $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 is not a function”的错误信息。

我尝试了几种不同的方法,但是我不能使用 ng-style 根据它们的数组索引有条件地设置 div 元素的背景位置。有谁知道我可以使这项工作的方法吗?谢谢。

【问题讨论】:

  • $scope.navigationStyleToilet 中有值吗?
  • 价值观?基本上,$scope.navigationStyleToilet 是一个 div 的 ng 样式。将重复生成 div,我想根据其数组索引有条件地为每个 div 设置不同的背景位置。顺便说一句,我已经更新了我的问题,因为我忘了提到我已经声明并实例化了 $scope.navigationStyleToilet = [];
  • 以下答案是根据更新后的问题!!!

标签: javascript css angularjs angularjs-scope angularjs-ng-repeat


【解决方案1】:

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

ng-style="navigationStyleToilet[o]"

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

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

ng-style="navigationStyleToilet[$index]"

【讨论】:

    【解决方案2】:

    首先,您不需要单独的函数。

    您可以将 ng-repeat 放在 categoryInfo 上,方法是将其更改为:

    $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

    您可能在值中缺少 px 或 %,因为它们在 'background-position' 属性中是必需的

    但正如您在上面 plunkr 中看到的(通过检查元素),两个 div 都有“背景位置”,那么它们也是重叠的:

    所以你可能正在寻找这样的东西:

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

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

    希望这会有所帮助。 :)

    【讨论】:

      猜你喜欢
      • 2018-05-02
      • 2017-06-25
      • 2018-09-05
      • 1970-01-01
      • 2023-04-01
      • 2012-10-23
      • 2016-07-12
      • 2015-11-23
      • 2015-03-13
      相关资源
      最近更新 更多