[英]AngularJS : ngRepeat in custom directive not updating
我创建了一个包含ng-repeat
的自定义指令。 如果我从指令触发模型更新,则ng-repeat
不会显示数据更改,直到视图中发生其他事情为止。 我确定数据已正确更新。 这是代码:
控制器:
app.controller('myCTRL', ['$scope', function ($scope) {
//the 'model':
$scope.data=[];
for (var i = 0; i < 9; i++)
$scope.data.push({
'val':i+1,
'pos':i+1
});
$scope.directiveOptions = {
changeData: function (from, to) {
//here is the data update:
var tmp= $scope.data[from].val;
$scope.data[from].val =$scope.data[to].val;
$scope.data[to ].val =tmp;
}
};
$scope.revertData = function () {
for (var i = 0; i < 9; i++)
$scope.data[i].pos = $scope.data[i].pos * -1;
};
}]);
视图:
<div ng-controller="myCTRL">
<div id="container" ng-my-directive='directiveOptions'>
<div ng-repeat="item in data | orderBy:'pos'" class="itemClass" >
<div>
{{item.val}}
</div>
</div>
</div>
<div ng-click="revertData()">revert</div>
</div>
指示:
app.directive('ngMyDirective', function () {
return {
restrict: 'A',
scope: {
directiveOptions: '=ngMyDirective'
},
link: function (scope, elem, attr) {
//...
elem.on(
'mouseup',
function (e) {
// here I call the data change, but ng-repeat doesn't update
var from=2, to=3;
if (scope.directiveOptions.changeData){
scope.directiveOptions.changeData(from, to);
}
}
);
//...
}
};
});
如果单击revertData
div,则可以看到更新的数据。 我必须在changeData
的末尾强制$apply()
或在ng-repeat
添加一个空的ng-mouseover=""
,但我不敢相信这些是最好的方法,它们似乎只是窍门。
我想念什么?
编辑
如@yarons所建议,在jQLite事件中使用$ evalAsync,数据更改涉及视图更新。 但我不确定这是最佳做法。 我正在从指令嵌套的ng-repeat访问$ scope变量。 该指令实现影响模型的DOM操作。 这是最好的方法吗?
如果我理解正确,那么您的数据将在mouseup
的事件侦听器回调上更改。 在这种情况下,您的数据会在Angular摘要循环之外更改,因此在您的Angle视图中不会更改。 尝试使用
elem.on(
'mouseup', function (e) {
scope.$evalAsync(function() {
var from=2, to=3;
if (scope.directiveOptions.changeData){
scope.directiveOptions.changeData(from, to);
}
});
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.