1

I am new to angular... in below code i need to use variable scope $scope.slugname inside Angular Factory(Test)..

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;
});
Sajeetharan
  • 186,121
  • 54
  • 283
  • 331
Shazvan Hanif
  • 373
  • 2
  • 20

1 Answers1

1

can't use scope variables inside factory. alternatively you can pass the scope variable as parameter to the factory function.

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;
});
Sachila Ranawaka
  • 28,742
  • 4
  • 48
  • 69