Search code examples
javascriptangularjsangularjs-scope

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


Solution

  • 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;