AngularJS在ng-repeat内部更改变量

时间:2016-01-13 21:22:46

标签: javascript angularjs mongodb angular-meteor

我正在尝试根据点击的按钮设置变量。

这是我的代码:

'use strict'

angular.module('myApp')
.controller('AlineacionCtrl', function ($scope, $meteor) {

  $scope.activeIndex = {index: 0};

  $meteor.subscribe('kits').then(function (){
    $scope.kits = $meteor.collection(Kits, false);
    $scope.activeCategory = $scope.kits[0].name;
    console.log($scope.activeCategory);
    $scope.log = function (){
      console.log($scope.activeCategory);
    };
  });

});

<section layout="row" layout-align="center center" layout-wrap ng-init="activeIndex; activeCategory">
  <md-button flex="auto" flex-sm="45" flex-xs="100" ng-repeat="kit in kits | orderBy: 'order'" ng-class="{active: (activeIndex.index == $index)}" class="md-raised">
    <a href="" ng-click="activeIndex.index = $index; activeCategory = kit.name; log()" class="bold">{{kit.name}}</a>
  </md-button>
</section>

ng-click="activeIndex.index = $index; activeCategory = kit.name"; log()

我正在尝试将activeCategory设置为当前点击的按钮kit.name,但每次log()函数都会记录第一个kit.name并且不会更改。

我在这里做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:2)

ng-repeat创建一个自己的范围。这就是你做什么的原因

activeCategory = kit.name;

您实际上并未更改$ scope.activeCategory,而是更改ng-repeat子范围内的变量activeCategory。

这样$ scope.activeCategory实际上永远不会被更改,因此它将始终返回第一个条目。

你要做的就是使用&#34;点缀&#34;变量以避免此问题。 这实际上是谷歌一直鼓励的。

尝试这样的事情:

angular.module('myApp')
.controller('AlineacionCtrl', function ($scope, $meteor) {

  $scope.activeIndex = {index: 0};
  $scope.activeCategory = { category: undefined };

  $meteor.subscribe('kits').then(function (){
    $scope.kits = $meteor.collection(Kits, false);
    $scope.activeCategory.category = $scope.kits[0].name;
    console.log($scope.activeCategory.category);
    $scope.log = function (){
      console.log($scope.activeCategory.category);
    };
  });

});

<section layout="row" layout-align="center center" layout-wrap ng-init="activeIndex; activeCategory">
  <md-button flex="auto" flex-sm="45" flex-xs="100" ng-repeat="kit in kits | orderBy: 'order'" ng-class="{active: (activeIndex.index == $index)}" class="md-raised">
    <a href="" ng-click="activeIndex.index = $index; activeCategory.category = kit.name; log()" class="bold">{{kit.name}}</a>
  </md-button>
</section>

在此处查看有关此问题的帖子: Webpack

并说明为什么在这里出现ng-model: Why don't the AngularJS docs use a dot in the model directive?