我有服务
app.service('myService', function() { this.list = []; this.execute = function() { //this.list is reachable here angular.forEach(AnArrayHere, function(val, key) { //this.list is not reachable here }); } }
即使在控制器中也可访问
function Ctrl($scope, myService) { $scope.list = myService.list; }
有人可以解释一下为什么在angular.foreach中无法访问“ this.list”吗?如何访问“ this.list”?
angular.forEach(请参阅http://docs.angularjs.org/api/angular.forEach)函数中的最后一个参数是的上下文this。因此,您需要这样的东西:
angular.forEach
this
app.service('myService', function() { this.list = []; this.execute = function() { //this.list is reachable here angular.forEach(AnArrayHere, function(val, key) { //access this.list }, this); } }