What is the best method for transferring $scope to a controller using ng-click?

The template I am working with looks like this:

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

When trying to invoke setImage() in the controller, an error is thrown: $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;

To resolve this issue, I tried adding $scope as a parameter in setImage($scope, img), but it did not work. Any suggestions on how to fix this would be greatly appreciated. Thank you!

Answer №1

Revamp your controller's dependency assignment approach by utilizing the this variable within the constructor.

Class BookController {
  constructor($scope, $stateParams, $http) {
    this.name = 'book';
    //Include
    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;

Answer №2

Check out this example for your JavaScript file:


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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Node.js Express server seems to be having trouble accessing static files

After successfully starting the express server, I encountered an issue when trying to load static files which resulted in an error message reading "Cannot GET /URL". The static files are located within a folder named "Login" and both the app.js and "Logi ...

Display a button within a table depending on the content of adjacent cells

Below is the code snippet I'm currently working with: <tbody *ngIf="packages"> <tr *ngFor="let package of packages"> <td class='checkbox'> <label class="css-control css-co ...

Creating dynamic <a> tags using JavaScript

My current view includes a div tag with 2 links - one for displaying the page in English and another for Arabic. I want to modify it so that if the page is already in English, only the Arabic <a> tag will show, and vice versa if the page is in Arabic ...

Retrieve dynamic data for Pivot in Devexpress AngularJS

I am currently working on an AngularJS web app where I am implementing a Pivot using devexpress, specifically utilizing the Field Chooser. You can find the example code here: In the provided example, static data is used. However, I need to fetch data dyna ...

What is the process of connecting two models in Mongoose?

In this scenario, we have two models - ProductModel and CategoryModel. The goal here is to establish a connection between creating a product (ProductModel) and assigning it to a category. The issue arises when the category field is not getting filled in t ...

Retrieving data from the parent controller's $scope once it has been loaded in Angular

In my Angular project, I encountered the following scenario: During the initialization process, I fetch JSON data from a database and assign it to a variable called "data". However, I want to access this "data" variable in a child controller that is nest ...

Tips for handling an incorrect date entry when a field loses focus in AngularJS

If I have an <input> field with the type='date' attribute in its untouched state, it displays mm/dd/yyyy as the date format. I am looking to see if there is a way to utilize AngularJS ng-blur directive to reset the field to this original fo ...

Having trouble with material-ui installation in React, Redux, and React-Router project

Guide: https://i.stack.imgur.com/k1UMV.png Due to using redux and react router, incorporating MuiThemeProvider at the top of the chain is a bit challenging. What would be the most effective method to integrate this particular library? This is my ReactDO ...

Navigating shadow dom elements in HTML with Selenium WebDriver

public WebElement retrieveShadowRootElement(WebElement element) { WebElement shadowRoot = (WebElement) ((JavascriptExecutor)driver) .executeScript("return arguments[0].shadowRoot", element); return shadowRoot; } WebElement rootElement= dri ...

Click anywhere outside the sidemenu to close it

I want the menu to behave like the side menu on Medium. When the side menu is open and the user clicks outside of #sidebar-wrapper, the side menu should close. Currently, I have to click the toggle X to close the menu. html <a id="menu-toggle" href="# ...

What could be the reason why my AJAX error is not displaying the exception from my Webmethod?

I am currently utilizing Google Chrome for my work tasks. After referring to , I attempted to throw an exception from a webmethod. However, no output is shown in the console.log. The only information I received is a generic error message from the network ...

Discovering all input elements by utilizing nextAll in jQuery

Here is the HTML structure: <div class="field phone"> <input type="text" maxlength="3" /> </div> <div class="field phone number1"> <input type="text" maxlength="3" /> & ...

Updating the style sheet of a selected menu item on an ASP.NET master page

I created an asp.net master page with a menu setup like this: <menu id="menu"> <nav id="main_nav"> <ul id="menu-primary"> <li ><a href="./">Home</a></li> <li><a href="staff.aspx"& ...

Auto-filling a form with the selected 'id' in Django using JavaScript or AJAX

I am a novice and I want the form to be autofilled when I select a vehicle ID from the template. Here are my models. class Fuel(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) previous_km = models.IntegerField(blank=False, nul ...

Incorporating a swisstopo map from an external source into an Angular

I am looking to integrate a swisstopo map into my angular 8 app. As I am new to angular, I am unsure how to include this example in my component: I have tried adding the script link to my index.html file and it loads successfully. However, I am confused a ...

Tips for utilizing the ng-filter Json [@attributes] with Angularjs

I'm trying to sort through sports feed based on sport ID, but the JSON feeds are structured with @attributes. JSON Feeds series: [ { @attributes: { id: "cdf590b4-0206-45b0-9122-20eae46a2b27", name: "Pakistan tour of Sri Lanka, 2015", year ...

When I attempt to connect to my local MongoDB database, including a specific port in the URI is preventing the connection from being

While testing a connection to a local DB using mongoose and mongodb, I encountered an issue. Whenever I include a port number in the URI passed to mongoose.connect(), I receive a connection refused error. async function connectDB() { const db = await m ...

The Angular menu items that have dropdowns attached are not showing up on the screen at all

I have been working on developing a complex Angular menu, and while I have made progress with the overall structure, I am stuck on a particular issue. The menu needs to display different options based on the user's role, such as "admin." However, desp ...

Using PHP functions in an AJAX request

I am currently attempting to execute a php loop upon clicking a radio button. I understand that ajax is necessary for this task, but as a beginner in ajax, I am struggling to achieve the desired result. Presently, I am unable to click the radio button at a ...

Unable to view images on Wordpress theme

I am currently facing an issue where some images in my asset folder are not displaying properly when I convert my HTML/CSS/JS template to Wordpress. The main problem is with the image that should show up when you first visit the website. Below is the CSS c ...