【问题标题】:use angular variable inside angular factory在角度工厂中使用角度变量
【发布时间】:2018-11-13 16:59:54
【问题描述】:

我是 Angular 的新手... 在下面的代码中我需要使用变量范围 $scope.slugname 在 Angular 工厂(测试)中..

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

【问题讨论】:

    标签: angularjs nginfinitescroll


    【解决方案1】:

    不能在工厂内使用范围变量。或者,您可以将范围变量作为参数传递给工厂函数。

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

    【讨论】:

    • var url = 'baseURL/?slug='+$scope.slugname; 改为 var url = 'baseURL/?slug='+name; 对..?
    • 是的。只需替换工厂内的范围变量
    • 当然。如果有帮助,请务必将其标记为答案。
    猜你喜欢
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 2017-03-09
    • 2013-08-16
    • 1970-01-01
    相关资源
    最近更新 更多