Once more delving into Angular.js $scope and controllers

After spending several hours trying to troubleshoot the issue with my angular $scope, I still can't seem to pinpoint what's wrong. I'm using Angular.js with Ionic in my app, and I believe the problem lies within Angular.

Within my app, I have a "add to wishlist" feature. When a user taps on "add to wishlist" in the product detail view, the product is added to the database using a service and webSQL. However, when the user navigates to the wishlist view, the saved products do not update accordingly.

The menu.html file contains an Ionic side-menu:

  <ion-side-menu side="left" expose-aside-when="large" width="72">
        <ion-content>
          <ion-list ng-controller="LeftMenuCtrl">
        <ion-item nav-clear menu-close ng-href="#/app/wish" ng-click="updateWishList()" ng-class="{'current': isActive('/app/wish')}">
          <span class="icon icon-menu-wish"></span>
        </ion-item>
      </ion-list>
    </ion-content>
  </ion-side-menu>

The "LeftMenuCtrl" manages the active menu item hover state. In the WishListView, I want to display the currently added products:

<ion-view hide-nav-bar="true" view-title="WISHLIST" ng-controller="WishlistCtrl">
  <div class="bar bar-header bar-stable">
    <div class="header-wrapper">
     //heading content here
    </div>
  </div>
  <ion-content class="has-header">
    <ion-item class="product-card" ng-repeat="product in products">
      <div class="card">
        EAN: {{product.ean}}
      </div>
    </ion-item>
  </ion-content>
</ion-view>

And the controller for the Wishlist:

app.controller("WishlistCtrl", function($scope, $state, productService) {

//get initial wishlist products

    productService.getWishlistProducts().then(function (products) {
      $scope.products = products;
    });

//update wishlist when user clicks on the navigation but does not properly update the $scope

    $scope.updateWishList = function () {
      productService.getWishlistProducts().then(function (products) {
        $scope.products = products;
      });
    };
  })

If anyone could shed some light on what's going wrong here, I would greatly appreciate it.

Edit: Here is the state configuration for the menu link:

  .state('app.wish', {
    url: "/wish",
    views: {
      'menuContent': {
        templateUrl: "templates/wish.html"
      }
    }
  })

Edit2: Upon refreshing the page, all added products show up eventually, leading me to think that the $scope.updateWishList() creates another $scope...

Edit3:

app.controller('ProductDetailCtrl', function($stateParams ,$state, $scope, productService, $ionicHistory, $ionicPopup) {
    $scope.addToWishlist = function(ean) {

      productService.addProductToWishlist(ean).then(function(response) {
        if(response == "OK") {
          var alertPopup = $ionicPopup.alert({
            title: 'product added to wishlist',
            template: 'You can go to your wishlist to see all your marked products'
          });
        }
      });
    };
})

Edit4: I have created a Plunker: http://plnkr.co/edit/0woPfN Although it's not functioning as expected, you can review the code there (unnecessary content removed).

Answer №1

The issue you are facing is that there are two declarations of the WishlistCtrl.

First declaration is in the app.js file:

.state('app.wish', {
    url: "/wish",
    views: {
      'menuContent': {
        templateUrl: "wish.html",
        controller: 'WishlistCtrl' //this is the first declaration
      }
    }
  })

Second declaration is in the HTML:

<ion-view hide-nav-bar="true" view-title="WISHLIST" ng-controller="WishlistCtrl">

To resolve this issue, simply remove one of the declarations.

Answer №2

Finally, I managed to make it work. Initially, in the StateProvider, I included a resolve method:

  .state('app.wish', {
    url: "/wish",
    views: {
      'menuContent': {
        templateUrl: "templates/wish.html",
        controller: 'WishlistCtrl',
        resolve: {
          products: function(productService) {
            return productService.getWishlistProducts()
          }
        }
      }
    }
  })

Also, to keep the model up-to-date when a new product is added to the wishlist:

  .controller("WishlistCtrl", function($scope, $state, productService, products) {

    //set wishlist products on controller load
    $scope.products = products;

    //update the wishlist when a new product is added
    $rootScope.$on('updatedWishList', function() {
      console.log('The list has been updated.');
      productService.getWishlistProducts().then(function (products) {
        $scope.products = products;
      });
    });
  })

It's simple once you figure it out :D

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

Troubleshooting "jest + enzyme + react16: The src attribute of <img> tag is not sending

Currently, I am utilizing jest along with enzyme for testing my react component titled "AnimateImage". This component includes an image element within it: import * as React from 'react'; import { PureComponent } from 'react'; interfac ...

Tips for troubleshooting objects within an Angular template in an HTML file

When I'm creating a template, I embed some Angular code within my HTML elements: <button id="btnMainMenu" class="button button-icon fa fa-chevron-left header-icon" ng-if="(!CoursesVm.showcheckboxes || (CoursesVm.tabSelected == 'curren ...

Display the output based on checkbox selection using JavaScript

I am working on a feature where I need to capture checkbox inputs using JavaScript and then store them in a PHP database. Each checkbox corresponds to a specific column in the database. If a checkbox is checked, I want to insert its value into the databa ...

What steps should be followed to make progress bar function properly?

Currently, I am delving into the world of Angular and attempting to craft a progress bar using a directive: var module = angular.module("app", []); module.directive("progressbar", function () { return { restrict: "A", link: function (s ...

Page Not Found: React and Express Route Not Found

I encountered an error while attempting to use the sign-up route: POST http://localhost:3001/sign-up 404 (Not Found). I searched for similar issues on StackOverflow but couldn't pinpoint the source of my problem... In the frontend, I am fetching the ...

Tips for accessing information from different sources within Vue 3

In my Vue 3 setup() method, I have an array [] stored as a constant. This array consists of X objects and represents the responses of a form. My goal is to showcase each object on a single dynamic page within our internal dashboard by using v-for in the t ...

The isPublic function in mean.js menu seems to be malfunctioning

While working on a mean.js application, I encountered an issue with displaying menu items in the top navbar. The menu items show up when the user is signed in, but not when they are signed out. According to the mean.js documentation, setting the 'isP ...

How can we generate 3 different arrays, each containing an equal number of items except for the last array, using VueJS?

Incorporating Bootstrap5 and VueJS 2, I am working on designing a layout of cards in a "pinterest-style" arrangement, as depicted in the following screenshot: https://i.sstatic.net/AvdWR.png To achieve the layout showcased above, the HTML markup required ...

Utilizing mixins with async components in VueJS

Currently, I am utilizing Webpack 2 to import components using a special syntax with require. Among the over 100 components available, only around 5-10 are used at any given time. These components share some common functionality such as props and lifecycl ...

What is the best way to retrieve JSON data using JavaScript within a loop?

I'm struggling to retrieve data from a JSON object. Here's the JSON structure I'm working with: var data = [ {"mes":{ "January":{ "Inversion":"1000","Fans":"1020"} ...

One method for routing pages in React Router is to have a shared component that is displayed on multiple pages, as well as a

My app.js consists of multiple pages with the navbar and sidebar as components, but my login page is different and does not include these elements. How can I use react-router to create separate routes for the login page without the sidebar and navbar, whil ...

A unique issue arises when custom geometry is registered in A-Frame but fails to render once added to a scene

I have developed custom functions to create non-hollow THREE.js geometries with phi length values that are less than 360. Now, I want to display them in an A-Frame scene (embedded within React). However, I am facing issues while trying to render them. Ini ...

How to add a date in Angular without needing to specify a scope or controller

I'm currently exploring different ways to incorporate a date in my HTML without relying on a scope or controller. I attempted the following approach, but unfortunately, it didn't yield the desired outcome. <p>Sample text {{Date.now().toStr ...

Tips for determining the final cost post discount entry

Calculate the final cost with discount Issue with OnChange event function CalculateDiscount() { var quantity = document.getElementById("ticket-count").innerText; var price = document.getElementById("item-price").innerText; var discount = document.getEle ...

Tips for intentionally refreshing or crashing a browser tab by utilizing the response from an AJAX request

Yesterday, we deployed new code to our production environment which included a polling mechanism using setInterval() in Javascript. This feature makes an AJAX request every 15 seconds to update clients with the server. Surprisingly, even though only around ...

Why isn't my mail carrier displaying the information about the founding year and revenue of my company?

My http requests in Postman display a null value for the schema number instead of the correct one. ``const mongoose = require('mongoose'); const OrganisationSchema = mongoose.Schema({ name: String, yearFounded: Number, revenue: Number }, ...

Executing asynchronous functions on a local Windows 10 machine with NodeJS

I am currently facing difficulty running an asynchronous function obtained from a Google example alongside Environment Variables on my Windows 10 system. I have set up a bucket on GCS and uploaded my .raw file. Furthermore, I have created a .env file with ...

I require redirecting my page once the execution is complete

I have encountered an issue where after executing this page, the database value is updated but it does not redirect to my intended page. Instead, it displays a blank white page. Can you please help me fix this problem? <? if($_POST['submit']) ...

Menu with a slider featuring three different choices

I am currently working on creating a box with a title and two arrows positioned to the left and right of the title. The goal is for the box to fade out when either arrow is clicked, and then fade in with the next option. I have a similar setup already impl ...

"Using the power of jQuery to efficiently bind events to elements through associative

I am attempting to link the same action to 3 checkboxes, with a different outcome for each: var checkboxes = { 'option1' : 'result1', 'option2' : 'result2', 'option3' : 'result3', }; ...