2016-01-13 42 views
1

我試圖根據點擊的按鈕設置一個變量。AngularJS更改ng-repeat內的變量

這裏是我的代碼:

'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並不會改變。

我在這裏做錯了什麼?

謝謝!

+0

爲什麼log函數放在'$ meteor.subscribe'裏面? –

+0

只是把它拿出來,仍然是相同的日誌。 –

+0

它只是返回集合的'名稱',在這種情況下,每次我按下按鈕時,無論哪一個都是第一個。 –

回答

2

ng-repeat創建一個自己的範圍。這就是爲什麼當你做

activeCategory = kit.name; 

你實際上並沒有改變$ scope.activeCategory,但NG-重複的子範圍變量activeCategory。

這種方式$ scope.activeCategory從來沒有真正被改變,因此它總是會返回第一個條目。

你必須做的是使用「虛線」變量來避免這個問題。 這實際上是由谷歌始終鼓勵。

嘗試這樣:

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> 

看到關於這個問題的一則訊息: Why don't the AngularJS docs use a dot in the model directive?

,爲什麼它在這裏NG-模型發生的說明: http://excellencenodejsblog.com/angularjs-directive-child-scope-ng-repeat-ng-model/