[英]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.