[英]AngularJS change variable inside an 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
都不會更改。
我在這里做錯了什么?
謝謝!
ng-repeat創建自己的作用域。 這就是為什么當你這樣做
activeCategory = kit.name;
您實際上並沒有更改$ scope.activeCategory,而是更改了ng-repeat子作用域上的變量activeCategory。
這樣,$ scope.activeCategory實際上從未更改過,因此它將始終返回第一個條目。
您要做的是使用“點分”變量來避免此問題。 實際上,這一直是Google一直鼓勵的。
嘗試這樣的事情:
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>
在這里看到有關此問題的文章: AngularJS文檔為什么不在model指令中使用點?
以及在ng-model中為什么會發生這種情況的說明: http : //excellencenodejsblog.com/angularjs-directive-child-scope-ng-repeat-ng-model/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.