1

I'm trying to set a variable depending on the button clicked.

Here's my code:

'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()

I'm trying to set activeCategory to be the current clicked button kit.name but everytime the log() functions logs the first kit.name and doesn't change.

What am I doing wrong here?

Thanks!

Johhan Santana
  • 2,336
  • 5
  • 33
  • 61

1 Answers1

2

ng-repeat creates a own scope. that's why when you do

activeCategory = kit.name;

you do not actually change $scope.activeCategory, but the variable activeCategory on the sub-scope of ng-repeat.

this way $scope.activeCategory never actually gets changed, hence it will always return the first entry.

what you have to do is do use a "dotted" variable to avoid this problem. this is actually encouraged by google all the time.

try something like this:

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);
    };
  });

});

and

<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>

see a post about this problem here: Why don't the AngularJS docs use a dot in the model directive?

and a description of why it occurs with ng-model here: http://excellencenodejsblog.com/angularjs-directive-child-scope-ng-repeat-ng-model/

Community
  • 1
  • 1
Patrick Kelleter
  • 2,631
  • 1
  • 13
  • 19