5 javascript angularjs angularjs-directive angularjs-ng-repeat
我有一个fooditems列表,$scope.raw我想在列中显示这些数据,所以我正在改变结构.我在sortStuff()函数中执行此操作并将更新的数据存储在其中$scope.allfood.sortStuff()每当有任何变化时都会有一个$ watch $scope.raw(我正在使用拖放来改变食物类别):
$scope.$watch('raw', function(){
$scope.allfood = $scope.sortStuff();
console.log($scope.allfood);
}, true);
Run Code Online (Sandbox Code Playgroud)
当食物被拖拽时会发生这种情况:
receive:function(event, ui) {
var issueScope = angular.element(ui.item).scope();
scope.$apply(function() {
var recp = _.find(scope.raw, function(lineitem){
return lineitem.name === issueScope.receipe.name;
})
recp.cat = scope.col.name;
})
$(ui.item).remove(); // remove DOM
}
Run Code Online (Sandbox Code Playgroud)
基本上,我在里面搜索正确的对象$scope.raw并改为cat食物的新类别.我也删除了dom元素,因为我指望ng-repeat来刷新视图.这似乎工作正常:$ watch中的console.log显示对象正在被移动到正确的类别,数据看起来应该是什么样子.但是,视觉上,ng-repeat不反映数据.
将项目从B拖动到C可以正常工作.将一个从A拖动到B,使得B中的两个项目消失...结果非常不一致,我不知道发生了什么.
出了什么问题?或者可能有任何建议,以更好的方式来做到这一点?
您的代码的问题在于该ng-repeat指令将该属性添加$$hashKey到列表中的每个元素。指令使用此属性将 DOM 元素与数组元素关联起来。
由于您通过引用传递元素,因此该ng-repeat指令将$$hashKey属性直接写入数组的对象中$scope.raw。一个简单的解决方法是在将对象插入到对象中之前复制对象$scope.allfood。
_.each($scope.raw, function(recp){
recp = _.clone(recp);
switch(recp.cat){
...
}
});
Run Code Online (Sandbox Code Playgroud)
现在ng-repeat更新了 的对象$scope.allfood,而 的对象$scope.raw保持不变。
查看更新的小提琴: