Angular 指令中的数据混乱
Data mess in Angular directive
几天来我一直在为这个问题苦苦挣扎。
问题是我的 angular 指令扰乱了我的数据模型。
为简单起见,我在这里创建了一个简单的示例:http://jsfiddle.net/hanspc/xxy4vh3v/
angular.module('vt.directives', [])
.directive('personType', [function () {
return {
restrict: 'A',
replace: true,
scope: {
personType: '@'
},
template: '<div class="{{pClass}}" style="height: 80px; width: 200px">Class: {{pClass}}<br>Type: {{personType}}</div>',
link: function (scope, elm, attrs) {
console.log(scope.personType);
scope.pClass = scope.personType == 'male' ? 'male-class' : 'female-class';
}
};
}]);
当我单击其中一个添加按钮时,它又向数据模型添加了一个人。问题是指令没有使用正确的数据值。如果您单击 'Add Anne',数据看起来是正确的 "outside" 指令,而不是 "inside"。根据数据,它应该 return 正确的 class 名称(和颜色),但添加的女性显示为蓝色(男性)。
而且无论您点击了多少按钮或点击了哪些按钮,只有前两个按钮是蓝色的。其余为红色。
有什么想法吗?
谢谢
您错误地使用了 track,因为您使用的是 unshift,并且元素的实际索引位置发生了变化。尝试为插入到数组中的每个对象添加一个唯一 ID,并以此代替跟踪。
这是有效的曲目:
<div style="float: left; height: 140px; width: 200px; border: 1px solid #cccccc; margin-bottom: 20px;" ng-repeat="p in data.persons">
几天来我一直在为这个问题苦苦挣扎。
问题是我的 angular 指令扰乱了我的数据模型。
为简单起见,我在这里创建了一个简单的示例:http://jsfiddle.net/hanspc/xxy4vh3v/
angular.module('vt.directives', [])
.directive('personType', [function () {
return {
restrict: 'A',
replace: true,
scope: {
personType: '@'
},
template: '<div class="{{pClass}}" style="height: 80px; width: 200px">Class: {{pClass}}<br>Type: {{personType}}</div>',
link: function (scope, elm, attrs) {
console.log(scope.personType);
scope.pClass = scope.personType == 'male' ? 'male-class' : 'female-class';
}
};
}]);
当我单击其中一个添加按钮时,它又向数据模型添加了一个人。问题是指令没有使用正确的数据值。如果您单击 'Add Anne',数据看起来是正确的 "outside" 指令,而不是 "inside"。根据数据,它应该 return 正确的 class 名称(和颜色),但添加的女性显示为蓝色(男性)。
而且无论您点击了多少按钮或点击了哪些按钮,只有前两个按钮是蓝色的。其余为红色。
有什么想法吗?
谢谢
您错误地使用了 track,因为您使用的是 unshift,并且元素的实际索引位置发生了变化。尝试为插入到数组中的每个对象添加一个唯一 ID,并以此代替跟踪。
这是有效的曲目:
<div style="float: left; height: 140px; width: 200px; border: 1px solid #cccccc; margin-bottom: 20px;" ng-repeat="p in data.persons">