你的问题与角度无关,而是与Javascript有关。
var arr = [] // arr is a pointer to an empty array
var things = arr // things is a pointer to the same empty array
arr = data // now arr points to data, but things still points to the empty array
您可以通过运行以下代码来说服自己:
var a = [1];
var b = a;
a = [2];
// Now if you console.log a and b, a === [2] and b === [1]
但是如果你操纵一个对象的属性
var a = { data: 1 }
var b = a;
a.data = 2;
// Now a.data and b.data are the same: 2
a = { data: 3 };
// Here we changed a, not its property, so a and b are not the same anymore
// a.data === 3 but b.data === 2
如果您了解这一点,那么有很多方法可以解决您的问题,例如:
angular.module('testApp')
.factory('Thing', function($http) {
var obj = {};
return {
things: obj,
get: function() {
$http.get('/api/things').success(function(data) {
obj.data = data;
});
}
};
})
在你的 HTML 使用中things.data
.
或者,如果您不想使用对象属性,而是直接使用数组,而不是替换指针,您只需更新数组的内容(因此 arr 仍然指向同一个数组):
angular.module('testApp')
.factory('Thing', function($http) {
var arr= [];
return {
things: arr,
get: function() {
$http.get('/api/things').success(function(data) {
for (var i in data) {
arr[i] = data[i];
}
});
}
};
})