我有一个对象,我在运行时向它添加一个函数,其值也在运行时生成(某种程度上)
//in my service
var model = {
id: 0,
name: 'one',
refs: {
list: [{id: 0, name: 'ref1'}, .... ]
}
}
//in controller
model.useRefs = function() { logRefs(model.refs.list); };
//in service
function logRefs(objectList) {
//getting an empty list here for objectList
var length = objectList.length;
for(var i = 0; i < length; i++) {
console.log(objectList[i].name);
}
}
出于某种原因,当调用函数 logRefs
时(通过调用 model.useRefs()
),objectList 参数只是一个空数组,但在以下情况下该数组具有值:该函数被分配给 useRefs
奇怪的是,我的应用程序的另一部分有同样的代码,并且它工作正常。
<小时/>我想我应该补充一点,我正在使用 Angular,其中一些代码位于 Controller 中,而其他部分位于服务中。
fiddle :https://jsfiddle.net/ahmadabdul3/s7qptz2s/1/
可悲的是......它在 fiddle 中工作,但在我的环境中不起作用......
最佳答案
将您的 model
对象和 logRefs
函数定义为“联合”服务:
(我将为应用程序、服务和 Controller 使用一些示例性名称 - 将它们替换为您当前的名称)
var myApp = angular.module('myApp', []);
// defining service
myApp.factory('myService', function() {
return {
model : {
id: 0,
name: 'one',
refs: {
list: [{id: 0, name: 'ref1'}, .... ]
}
},
logRefs: function(objectList) {
//getting an empty list here for objectList
var length = objectList.length;
for(var i = 0; i < length; i++) {
console.log(objectList[i].name);
}
}
};
});
// controller
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
myService.model.useRefs = function() {
myService.logRefs(myService.model.refs.list);
};
}]);
关于javascript - 在 JavaScript 中赋值后项目失去值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35022414/