我有这个html:
<div ng-app='myApp'>
<div ng-controller='testCtrl'>
<h3>All possesions</h3>
{{possessions}}
<h3>Green cars</h3>
{{greenishCars}}
</div>
</div>
这个脚本:
angular.module('myApp', [])
.factory('getPossessionsService', ['$timeout',
function($timeout) {
var possessions = {};
$timeout(function() {
possessions.cars = [{
model: "Mazda 6",
color: "lime green"
}, {
model: "Audi A3",
color: "red"
}, {
model: "Audi TT",
color: "green"
}, {
model: "Volkswagen Lupo",
color: "forest green"
}];
possessions.jewelry = [{
type: "ring",
metal: "gold"
}, {
type: "earring",
metal: "silver"
}];
}, 1000);
return possessions;
}
])
.controller('testCtrl', ['$scope', 'filterFilter', 'getPossessionsService',
function($scope, filterFilter, getPossessionsService) {
$scope.possessions = getPossessionsService;
$scope.greenishCars = filterFilter($scope.possessions.cars, carColorIsGreenShade);
function carColorIsGreenShade(car) {
return ['green', 'forest green', 'lime green'].indexOf(car.color) != -1;
}
}
]);
我试图让 $scope.greenishCars 在数据可用时正确更新,但事实并非如此。我知道这是因为 $scope.possessions.cars 是一个数组,因此不是对数据的引用,因此它不会更新。但是我应该如何更改我的脚本以便 greenishCars 在数据到达时得到更新?我猜我应该“直接”使用 $scope.possessions,但我不太明白应该如何很好地重写它......
看到这个plunk。
编辑:关于选择哪个答案的想法 正如 Oliver 和 MajoB 的答案中的评论一样,我最终同时使用了过滤器和 watch 。在我的特殊情况下,对数据的请求是在另一个地方发出的(不是在我的相关页面的 Controller 中),因此要解决 promise 的问题并不那么容易(按照奥利弗的建议,使用promise.then) ,因此我使用了 watch 。但对于 watch 来说,有几点需要注意。如果您要监视的变量不在作用域内,则必须通过从函数返回该变量来提供该变量。如果你想观察现有属性的变化(比如有人用不同的颜色重新绘制了我现有的马自达 6),那么所有的 watch-answer 都不起作用,因为你需要在调用 $watch 时添加“true”。当您将“true”作为第二个参数添加到 $watch 时,它会监视变量实际值的变化,并且还会检查对象/数组深处的值(如果不检查引用,请参阅 this blog )。我最终为我的现实用例使用了这个 Controller /$watch(这与上面的示例有点不同,并且基于 Olivers filter-plunk ),它看起来像这样(更改为适合 plunk) :
.controller('testCtrl', ['$scope', 'greenFilter', 'getPossessionsService',
function($scope, greenFilter, getPossessionsService) {
var none-scope-possessions = getPossessionsService; // I do not want to expose all properties on the scope....
$scope.greenishCars = [];
$scope.$watch(function() {return none-scope-possessions.cars}, function(newValue){
if (newValue) {
$scope.greenishCars = greenFilter(newValue);
}
},true);
}
]);
最佳答案
您可以观察数据变化:
$scope.$watch('possessions.cars', function(){
$scope.greenishCars = filterFilter($scope.possessions.cars, carColorIsGreenShade);
});
关于AngularJS:尝试使过滤器处理延迟数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25831663/