2015-02-09 76 views
1

我一直在努力解决这个问题几天。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按钮中的一个,它增加了多一个人的数据模型。问题是该指令没有使用正确的数据值。如果点击“添加安妮”,数据看起来就在指令的“外部”,而不是“内部”。它应该根据数据返回正确的类名(和颜色),但添加的女性显示为蓝色(男性)。

而且无论您点击多少个或哪个按钮,前两个都是蓝色。其余的是红色的。

任何想法?

感谢

回答

1

您使用的是错误的,因为你使用不印字,和你的实际元素的索引位置发生了变化轨迹。尝试为每个插入到数组中的对象添加一个唯一的ID,然后通过它进行跟踪。

http://jsfiddle.net/kku170cm/

这里的赛道由工作:

<div style="float: left; height: 140px; width: 200px; border: 1px solid #cccccc; margin-bottom: 20px;" ng-repeat="p in data.persons">