AngularJS is having difficulty identifying the function

Encountering a similar issue to the one discussed in:

The $scope variable is undefined unless I forced it to retrieve from service again

AngularJS throws the following error when trying to call a function from a service:

TypeError: $scope.watchlist.addStock is not a function

This is the code snippet for the controller:

angular.module('stockDogApp')
  .controller('WatchlistCtrl', function ($scope,$routeParams,$modal,WatchlistService,CompanyService) {
    $scope.companies = CompanyService.query();
    $scope.watchlist = WatchlistService.query($routeParams.listId);
    console.log($scope.watchlist);
    $scope.stocks = $scope.watchlist.stocks;
    $scope.newStock = {};
    var addStockModal = $modal({
      scope : $scope,
      templateUrl : 'views/templates/addstock-modal.html',
      show: false
    });

    $scope.showStockModal = function(){
      addStockModal.$promise.then(addStockModal.show);
    };

    $scope.addStock = function(){
      $scope.watchlist.addStock({
        listId : $routeParams.listId,
        company: $scope.newStock.company,
        shares: $scope.newStock.shares
      });
      addStockModal.hide();
      $scope.newStock = {};
    };

Checking the log for $scope.watchlist - the function appears to be present within the object:

Object {name: "Saklep", description: "Saklep", id: 0, stocks: Array[0]}
addStock: function(stock)
arguments: (...)
caller: (...)
length: 1
name: ""

Here's the HTML markup for the modal window:

<div class="modal" tabindex="-1" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" ng-click="$hide()">&times;</button>
        <h4 class="modal-title">Add New Stock</h4>
      </div>

      <form role="form" id="add-stock" name="stockForm">
        <div class="modal-body">
          <div class="form-group">
            <label for="stock-symbol">Symbol</label>
            <input type="text"
              class="form-control"
              id="stock-symbol"
              placeholder="Stock Symbol"
              ng-model="newStock.company"
              bs-options="company as company.label for company in companies"
              bs-typeahead
              required>
          </div>
          <div class="form-group">
            <label for="stock-shares">Shares Owned</label>
            <input type="number"
              class="form-control"
              id="stock-shares"
              placeholder="# Shares Owned"
              ng-model="newStock.shares"
              required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit"
            class="btn btn-success"
            ng-click="addStock()"
            ng-disabled="!stockForm.$valid">Add</button>
          <button type="button"
            class="btn btn-danger"
            ng-click="$hide()">Cancel</button>
        </div>
      </form>
    </div>
  </div>
</div>

EDIT: Including the watchlist Service:

angular.module('stockDogApp')
  .service('WatchlistService', function () {
    var loadModel = function(){
      var model = {
      watchlists : localStorage['StockDog.watchlists'] ? JSON.parse(localStorage['StockDog.watchlists']) : [],
      nextId : localStorage['StockDog.nextId'] ? parseInt(localStorage['StockDog.nextId']) : 0
    };
    _.each(model.watchlists,function(watchlist){
      _.extend(watchlist,WatchlistModel);
      _.each(watchlist.stocks,function(stock){
        _.extend(stock,StockModel);
      });
    });
    return model;
  };

  var StockModel = {
    save: function(){
      var watchlist = findById(this.listId);
      watchlist.recalculate();
      saveModel;
    }
  };

  var WatchlistModel = {
    addStock: function(stock){
      var existingStock = _.find(this.stocks,function(s){
        return s.company.symbol === stock.company.symbol;
      });
      if (existingStock){
        existingStock.shares += stock.shares;
      }else{
        _.extend(stock,StockModel);
        this.stocks.push(stock);
      }
      this.recalculate();
      saveModel();
    },

Answer №1

It was discovered that Angular-Yeoman generates a controllerAs function in app.js, causing a conflict.

  .when('/watchlist/:listId', {
    templateUrl: 'views/watchlist.html',
    controller: 'WatchlistCtrl',
    // controllerAs: 'watchlist'
  })

By commenting out the controllerAs line, the issue was resolved.

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 Date.UTC function is not providing the correct output

While attempting to change Unix timestamps into a more understandable format, I used Date.UTC(2017,09,23);. When running this code, it returned 1508716800000. However, upon verifying on the website , the displayed result showed October 23, 2017 instead o ...

Issue with Internet Explorer 8 preventing the ability to dynamically create buttons

When attempting to dynamically create a button in Internet Explorer, there is an error whereas it works perfectly in Firefox. var deleteButton = document.createElement('input'); ratingSliderContainer.appendChild(deleteButton); deleteButton.set ...

Is there a way to use code to target a mesh in a three.js scene when a button is clicked?

When a button is clicked, I want a Three.js Mesh to be focused based on the button. For example, when the "view top" button is clicked, the mesh should be focused from the top. Is there an inbuilt method in three.js to focus a mesh or how can I calculate ...

How can I identify a pattern in JavaScript that may include a certain character but cannot end with it using regex?

I am a beginner in the world of regular expressions. Despite my efforts to find a solution for my specific case, I have not been successful. I have tested several ideas that I came across, but none of them have worked for me. I have a unique repetitive pa ...

Adjust the background color of a column in HTML based on its corresponding color name

Is there a way to change the background color of a column in an HTML table if the value is green? We want the background color to reflect the color name. The data will be retrieved from a web service. Here is the HTML code used to display the data in the ...

Unable to implement multiple draggable inner objects using Angular 5 and dragula library

After struggling for the past few days, I can't seem to get it to work... Here is a brief explanation of my issue: In this example, I have an array of objects structured like this: public containers: Array<object> = [ { "name": "contain ...

Is it possible for a function within a nodejs module to be defined but display as undefined upon access?

I am currently developing a Discord bot using NodeJS and TypeScript, and I'm facing an issue while trying to import custom modules in a loop with the following code: const eventFiles = fs.readdirSync("./src/events/").filter((file: string) =& ...

Using a custom function, automatically initiate audio playback when an Android WebView JS loads

I have a unique JS function specifically designed for the audio tag, which also controls the progress bar. It works perfectly when I click on the associated tag <a onclick="playSound(1)">. However, if I try to initiate it on page load, the function s ...

Why is the text not displaying in ReactJS when using Enzyme?

Can you please assist me in understanding why my test case is not running in React when using enzyme? I have installed enzyme js and followed this tutorial at Below is the code I am using: import React from 'react'; import Hello from './ ...

Error encountered with the OffsetWidth in the Jq.carousel program

I am encountering an issue that I cannot seem to figure out. Unexpected error: Cannot read property 'offsetWidth' of undefined To view the code in question, click on this link - http://jsfiddle.net/2EFsd/1/ var $carousel = $(' #carouse& ...

Is there a way to ensure my Vue variable is declared once the page has fully loaded?

I have implemented a v-for loop in my code: <div v-for="(user, index) in users" :key="index" :presence="user.presence" class="person"> <span class="cardName h4">{{ user.name }}</span> ...

Obtaining varied outcomes while printing filtered information

As a beginner in React.js using hooks, I prefer to learn through hands-on coding. My query revolves around fetching data from a specific URL like ksngfr.com/something.txt and displaying it as shown in the provided image (I only displayed numbers 1-4, but t ...

Problems with Wordpress AJAX search functionality

I am currently working on implementing a search feature using AJAX to dynamically load posts. However, I am facing an issue where the results are not being displayed. This code snippet was adapted from another source and modified based on private feedback ...

How to Use Jquery UI Datepicker

Currently, I am delving into the world of JavaScript and have grasped some understanding of it. As I created a webpage with a date entry field, I require a calendar feature to enable date selection. The jquery UI datepicker (http://jqueryui.com/datepicker) ...

Enhancing the user experience of the dropdown component through improved

I have developed an accessibility feature for a dropdown component that dynamically populates values in the options menu only when the dropdown is opened. This means that it compiles the template on the fly and attaches it to the dropdown box. Dropdown HT ...

Tips for displaying axios status on a designated button using a spinner

Utilizing a v-for loop to showcase a list of products retrieved from an API request. Within the product card, there are three buttons, one for adding items to the cart with a shopping-cart icon. I aim for the shopping-cart icon to transform into a spinner ...

Getting js.map Files to Function Properly with UMD Modules

I am experiencing an issue with debugging TypeScript files in Chrome and Firefox. Specifically, when trying to debug the MapModuleTest.ts file, the debugger seems to be out of sync with the actual JavaScript code by two lines. This discrepancy makes settin ...

"Unlock the power of Google Maps with a JavaScript API key

I am currently using a Cordova application and have obtained a browser key for the map feature. <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBHJxzPHD_egYnhxntqcvfem35YRjruzAg&callback=initMap"> </script& ...

Skip a single test from a suite in Firefox using Protractor automation framework

I have a collection of tests in my tests folder, all named with the convention ending in spec.js. By using the */spec.js option in the Config file, I am able to run all tests seamlessly. However, I encountered an issue where I needed to skip running a spe ...

What is causing the error to occur during the installation of the NestJS Client?

Encountered an error while attempting to install the nestjs client, and I'm completely puzzled by this issue. PS C:\Users\meuser> npm i -g @nestjs/cli npm ERR! code ETARGET npm ERR! notarget No matching version found for @angular- ...