代码之家  ›  专栏  ›  技术社区  ›  Shazvan Hanif Fluffeh

在角度工厂内使用角度变量

  •  1
  • Shazvan Hanif Fluffeh  · 技术社区  · 6 年前

    我是新来的角度… 在下面的代码中,我需要使用变量作用域 $scope.slugname 内角工厂(测试)

    var myApp = angular.module('myApp', ['infinite-scroll']);
    
    myApp.controller('DemoController', function($scope, Test) {
      $scope.slugname ="slugname";
      $scope.test = new Test();
    });
    
    myApp.factory('Test', function($http) {
      var test = function() {
        this.items = [];
        this.busy = false;
        this.after = '';
      };
    
      Test.prototype.nextPage = function() {
        if (this.busy) return;
        this.busy = true;
    
        var url = 'baseURL/?slug='+$scope.slugname;  //<-- I need to use variable($scope.slugname) here
        $http.jsonp(url).success(function(data) {
          var items = data.data.children;
          for (var i = 0; i < items.length; i++) {
            this.items.push(items[i].data);
          }
          this.after =  this.items[this.items.length - 1].id;
          this.busy = false;
        }.bind(this));
      };
    
      return Test;
    });
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Sachila Ranawaka    6 年前

    无法在工厂内使用范围变量。或者,可以将scope变量作为参数传递给factory函数。

    myApp.controller('DemoController', function($scope, Test) {
      $scope.slugname ="slugname";
      $scope.test = new Test($scope.slugname );
    });
    
    myApp.factory('Test', function($http) {
      var test = function() {
        this.items = [];
        this.busy = false;
        this.after = '';
      };
    
      Test.prototype.nextPage = function(name) {
        if (this.busy) return;
        this.busy = true;
    
        var url = 'baseURL/?slug='+$scope.slugname;
        $http.jsonp(url).success(function(data) {
          var items = data.data.children;
          for (var i = 0; i < items.length; i++) {
            this.items.push(items[i].data);
          }
          this.after =  this.items[this.items.length - 1].id;
          this.busy = false;
        }.bind(this));
      };
    
      return Test;
    });