我正在修改服务内部的数组,同时绑定到指令中的服务属性。现在我想从数组中删除一个项目,但我无法Array.filter
工作。我不确定这是因为Array.filter
是异步的,还是因为它返回一个新数组而不是修改原始数组或$digest周期。一个常见的 for 循环确实有效,但是由于我阅读了更多声明性数组方法的优点,我想我会问你为什么它不起作用。
命令
(function () {
"use strict";
function MyDirective(MyService) {
return {
restrict: "E",
templateUrl: "template.html",
scope: {
limit: "="
},
link: function (scope, element, attrs) {
scope.array= MyService.array;
scope.removeItem = function (index) {
MyService.removeItem(index);
};
}
};
}
angular
.module("Module", [])
.directive("myDirective", ['MyService', MyDirective]);
}());
使用 Array.filter 的服务
(function () {
"use strict";
function MyService() {
var array = [];
function removeItem(idx) {
array = array.filter(function(item) {
return item.index !== idx;
});
}
return {
array: array,
removeItem: removeItem
};
}
angular
.module("Module")
.factory("MyService", [MyService]);
}());
带 for 循环的服务
(function () {
"use strict";
function MyService() {
var array = [];
function removeItem(idx) {
for(var i = 0; i < array.length; i++) {
if(array[i].index === idx) {
array.splice(i, 1);
break;
}
}
}
return {
array: array,
removeItem: removeItem
};
}
angular
.module("Module")
.factory("MyService", [MyService]);
}());
谢谢
编辑:为了澄清我所说的"它不起作用"的意思,UI 不会更新,当我输出 Array.filter 之前和之后的数组长度时,它的大小仍然相同。我也检查了下次删除项目时,它仍然和开头一样。
重新赋值变量时,对该变量的引用不会自动更新以引用新变量。
当您注入服务时,它会返回您从服务函数返回的对象,该对象有两个属性,一个空的array
数组和一个名为 removeItem
的函数。 当你调用 removeItem
时,它会在函数作用域中设置 array
var 的值,但不会改变返回对象的值。 试试这个:
function MyService() {
var obj = {
array: [],
removeItem: function removeItem(idx) {
obj.array = obj.array.filter(function(item) {
return item.index !== idx;
});
}
};
return obj;
}