boooni
boooni

Reputation: 153

How to pass $scope to controller via ng-click?

So I have the following template:

 <div class="book-thumbs">
   <div class="book-pic" ng-repeat="img in book.images">
     <img ng-src="{{img}}" ng-click="vm.setImage(img)">
   </div>
 </div>

In controller I am trying to invoke setImage(), but I get an error: $scope is not defined.

class BookController {
  constructor($scope, $stateParams, $http) {
    this.name = 'book';
    $scope.bookId = $stateParams.bookId;
    this.getBookInfo($http, $stateParams, $scope);
  }

  getBookInfo($http, $stateParams, $scope) {
    $http.get('books/' + $stateParams.bookId + '.json').success(function(data) {
      $scope.book = data;
      $scope.mainImageUrl = data.images[0];
    });
  }

  setImage(imageUrl) {
    $scope.mainImageUrl = imageUrl;
  }
}

BookController.$inject = ['$scope', '$stateParams', '$http'];
export default BookController;

How can I fix it? If I try to add $scope as a param in setImage($scope, img) nothing changes. Thank you

Upvotes: 0

Views: 122

Answers (2)

Change the way that your access and assign the dependencies in you controller using the this variable in your contructor.

Class BookController {
  constructor($scope, $stateParams, $http) {
    this.name = 'book';
    //Add
    this.$scope = $scope;
    this.$stateParams = $stateParams;
    this.$http = $http;

    this.$scope.bookId = $stateParams.bookId;
    this.getBookInfo();
  }

  getBookInfo() {
    var that = this;
    this.$http.get('books/' + this.$stateParams.bookId + '.json').success(function(data) {
      that.$scope.book = data;
      that.$scope.mainImageUrl = data.images[0];
    });
  }

  setImage(imageUrl) {
    this.$scope.mainImageUrl = imageUrl;
  }
}

BookController.$inject = ['$scope', '$stateParams', '$http'];
export default BookController;

Upvotes: 2

Naman Kheterpal
Naman Kheterpal

Reputation: 1840

Try this as ur JS file:

    "use strict";
   var BookController = (function () {
function BookController($scope, $stateParams, $http) {
    this.$scope = $scope;
    this.$stateParams = $stateParams;
    this.$http = $http;
    this.name = "";
    this.name = 'book';
    $scope.bookId = $stateParams.bookId;
    this.getBookInfo($http, $stateParams, $scope);
}
BookController.prototype.getBookInfo = function ($http, $stateParams,   $scope) {
    $http.get('books/' + $stateParams.bookId + '.json').success(function (data) {
        $scope.book = data;
        $scope.mainImageUrl = data.images[0];
    });
};
BookController.prototype.setImage = function (imageUrl) {
    this.$scope.mainImageUrl = imageUrl;
};
return BookController;
}());
BookController.$inject = ['$scope', '$stateParams', '$http'];
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = BookController;

Upvotes: 1

Related Questions