[英]Angular does not save the $scope.$watch order
我有一個代碼,負責對控制器中的元素進行排序。 這是代碼:
$scope.$watch('applications', function (applications) {
if (angular.isArray(applications) && applications.length !== 0) {
var landing_app = _.findWhere(applications, {
area_name : $scope.landingAreaName
});
applications = _.reject(applications, function(app){
return app.id == landing_app.id;
});
applications.unshift(landing_app);
}
});
當我console.log
applications
變量時-它具有正確的元素順序。 但是視圖中沒有維護它。 怎么了
更新:
當我使用此代碼時:
$scope.$watch('applications', function (applications) {
if (angular.isArray(applications) && applications.length !== 0) {
applications.sort(function (a) {
return a.area_name !== $scope.landingAreaName;
});
}
});
它的確會更改應用程序的順序,但這不是我想要的順序。
問題是在JS中變量是通過值而不是引用傳遞的-因此您對application
的分配僅是本地的:
var x = 3;
(function (x) {
x++; // x = 4
}(x));
// here, back to x = 3
因此,這就是“點規則”來自角度的原因:
var obj = {x: 3};
(function (obj) {
obj.x++; // obj.x = 4
}(obj));
// obj.x is still 4 here, because obj's **contents** weren't copied.
在這種情況下,最簡單的解決方案是修改$scope
:
$scope.applications = _.reject(...);
注意:任何破壞性操作都將起作用(例如unshift
),因為它會對內容起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.