在angular和javascript中使用父范围变量

时间:2014-02-12 17:20:25

标签: javascript angularjs variables

我有这个javascript代码:

myApp.factory('Reddit', function($http) {
  var Reddit = function() {
    this.items = [];
    this.busy = false;
    this.after = '';
  };

  Reddit.prototype.nextPage = function() {
    console.log(this.items);// []
    $http({method: 'GET', url: url}).
    success(function(data, status, headers, config) {
      console.log(this.items); // undefined ?? how to access to items list
    })

如何访问success功能中的项目列表?

1 个答案:

答案 0 :(得分:1)

尝试在定义局部变量时将其分配给局部变量。应该在您的成功函数中定义该局部变量。

Reddit.prototype.nextPage = function() {
    console.log(this.items);// []
    var localItems = this.items; // if it is defined here, then alias it to a local var ( you can rename it to whatever)
    $http({method: 'GET', url: url}).
    success(function(data, status, headers, config) {
      console.log(this.items); // undefined ?? how to access to items list
      console.log(localItems); // should work
    })

我假设你想要访问整个对象,在这种情况下你可以只是别名this

Reddit.prototype.nextPage = function() {
    var obj = this;
    $http({method: 'GET', url: url}).
    success(function(data, status, headers, config) {
      obj.items.push('xxx');
    });

这是一个plunkr,显示构建不同Reddit列表的items对象的多个实例:example。务必检查控制台。