在javascript中赋值后项目失去价值

时间:2016-01-26 19:38:28

标签: javascript angularjs

我有一个对象,我在运行时添加一个函数,其值也是在运行时生成的(有点像)

//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,而且其中一些代码在控制器中,而其他部分则在服务中。

小提琴:https://jsfiddle.net/ahmadabdul3/s7qptz2s/1/

可悲的是......它在小提琴中工作,但不在我的环境中工作......

2 个答案:

答案 0 :(得分:0)

将您的model对象和logRefs功能定义为“联合”服务:
(我将为应用程序,服务和控制器使用一些示例性名称 - 用当前名称替换它们)

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); 
    };
}]);

答案 1 :(得分:0)

好吧 - 我不知道为什么,但改变代码工作。即使我在顶部的代码工作在小提琴,而不是在我的环境中工作,以下工作对我来说:

我改变了这个:

model.useRefs = function() { logRefs(model.refs.list); };

到此:

model.useRefs = assignUseRefs(model.refs.list);

function assignUseRefs(refs) {
  return function() {
    return logRefs(refs);
  }
}

为什么有角度,为什么......(或者我应该责备javascript)