Angular: Having trouble accessing method within scope

I am attempting to utilize a method from my $scope controller, which is imported from a Factory, and execute it using the onclick method in an Ionic-based HTML.

However, I am encountering the issue of getting undefined and I am unsure of the reason behind it, as other variables from $scope (like userid) are accessible. Could this be a scope hierarchy problem? Despite reading numerous articles, I am still stuck. Thank you for any assistance.

Here is the Controller code:

var mod = angular.module('Baybee.controller.nameList', []);

mod.controller('NameListCtrl', function ($scope, AllNamesList, UidGenerator, $localstorage) { 
//importing list of names from Factory and unique user-id
$scope.namesFromService = AllNamesList.getList('AllNamesList');
$scope.userid = UidGenerator;
// test functions which I wasn't able to execute on 'onclick' method. scope.saveName should be that I wanted to use originaly
$scope.saveName = AllNamesList.transferName;
$scope.testb = function () {
  console.log('working!');
  };
});    

And here is the Factory code:

var mod = angular.module('Baybee.factory.allNamesList',['ionic'])

.factory('AllNamesList', function($localstorage) {
// 3 more list available as variables, here is just one
var AllNamesList = {

names: [
  {
    "name": "Jakub",
    "set": [
      "CzechCalendar",
      "Top10Cz2015",
      "Top50Cz2010"
    ],
    "properties": {
      "sex": "male",
      "origin": "Hebrew",
      "description": "Comes from Hebrew, יַעֲקֹב (Yaʿqob, Yaʿaqov, Yaʿăqōḇ)"
    },
    "popularity": [
      {
        "Cz": {
          "2011": "10",
          "2012": "7",
          "2013": "6",
          "2014": "6",
          "2015": "7"
        }
      }
    ]
  }
// more names here
]
};


return {
// returns right list with names based on string argument
getList: function(a) {
  switch (a) {
    case "AllNamesList":
      return AllNamesList;
      break;
    case "loveNameList":
      return loveNameList;
      break;
    case "maybeNameList":
      return maybeNameList;
      break;
    case "noGoNameList":
      return noGoNameList;
      break;
    default:
      console.log("Sorry, can't find list with names");
  }
},
// I would like to use this function on onlick method to transfer object with name properties to the right list (
transferName: function(name, listFrom, listTo){
  // saving both list names into local memory
  for (i = 0; i < listFrom.length; i++) {
      if (name = listFrom[i]) {
        listTo.push(listFrom[i]);
          console.log(listFrom);
        listFrom.splice(i, 1);
          console.log(listTo);
      }
    else {
        console.log('Cannot find: ' + name + ' in ' + listFrom);
      }
   }

  }

 }

});

Lastly, the HTML Body:

<body ng-app="baybee">

<ion-pane ng-controller="NameListCtrl">
    <ion-header-bar class="bar-energized" >
        <h1 class="title" >Baybee</h1 >
    </ion-header-bar >
    <ion-content >

        <ion-list >
      <div ng-repeat="names in namesFromService track by $index">
            <ion-item ng-repeat="(key, value) in names"
                on-swipe-right=""
                on-swipe-left=""
          //I would like to execute any function from scope here, but Im getting undefined
                //onclick="testb()"
                //onclick="saveName(name, 'list1', 'list2')"

        <h2>{{value.name}}</h2>
        <p>{{value.properties.origin}}</p>
      </ion-item>
      </div>
        </ion-list >

    </ion-content >
</ion-pane >
</body >

Answer №1

My HTML code contains a mistake - I mistakenly used the onclick method instead of ng-click.

ng-click="saveName(name, 'list1', 'list2')"

Thank you

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

Time taken to execute all the tests using the karma runner

We have recently transitioned to running unit tests remotely using browserstack across multiple browsers and operating systems with the help of the karma-browserstack-launcher plugin. The current output of our test run appears as follows: $ grunt unit:re ...

I am seeking assistance in resolving issues with my HTML and JavaScript code

I'm currently working on creating a code that changes the value of a variable and updates some text when a button is clicked. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <p id=" ...

Tips for addressing lag problems in my Three.js game as time progresses

My game in Three.js doesn't start off with any lag, but after a few minutes, the performance begins to slow down on computers running it. I've tried reviewing my code and checking my arrays, adjusting values to troubleshoot, but so far, nothing s ...

I am having issues with my JavaScript code, I could really use some assistance

Currently, I am developing a custom file search program. The goal is to have a textarea where users can input text, which will then generate a clickable link below it. However, I am facing issues with the current implementation. Below is the snippet of my ...

A guide to playing a series of audio files in succession using the Ionic Media plugin

I have been attempting to create a playlist of multiple audio files using the Ionic media plugin from here. However, I am struggling to achieve this without resorting to using a timeout function. Here is my current approach: playOne(track: AudioFile): Pr ...

What is the process for calculating the total sum of input values utilizing JavaScript?

My JavaScript skills are not perfect, and I'm struggling to calculate the total sum of values in the amount input boxes without refreshing the page. Can someone assist me with this challenge? Thank you. function Calculat ...

Error: Variable undefined in nested directive's scope

My goal is to create a smart-table directive from a custom directive that I have created: <div ng-controller="myContrtoller"> <containing-directive></containing-directive> </div> The directive definition: angular.module('a ...

When a cross-domain iframe is loaded in a private browser, it automatically logs the user out

I've been collaborating with a client to create a unique standalone website on a subdomain. They have requested that I utilize their API to initiate a straightforward post request when a user clicks a button. However, the client prefers the user to ut ...

Relocating JavaScript scripts to an external file on a webpage served by Node.js' Express

When using Express, I have a route that returns an HTML page like so: app.get('/', function(req, res){ return res.sendFile(path.resolve(__dirname + '/views/index.html')); }); This index.html file contains multiple scripts within t ...

Is it possible to make each letter on a page a different color using JavaScript? I've noticed that there is always an additional set of span tags before each opening tag on the page

Page hosted using Google Drive Within the JS code: var doc_part = false; //denotes if a character is not part of the visible document var page_body; //function to generate random rgb values function randomInt(max, min) { return Math.floor((Math.ran ...

the async function fails to run

fetchData = async () => { try { //Accessing data from AsyncStorage let car = await AsyncStorage.getItem('CAR') this.state.DatabaseCar=[]; this.state.DatabaseCar = JSON.parse(car); alert(this.state.Da ...

Developing a customized autosuggest feature using AJAX with comprehensive keyboard accessibility

Has anyone tried building their own AJAX auto suggest text box with full keyboard support? I've managed to create the auto suggest feature by connecting to a SQL DB and displaying results, but the only way to interact with the search results is throu ...

retrieve information provided by the user

When a user inputs a date into #dateUserInput and clicks the button, I want the fetch function to retrieve the appropriate image for that date. However, an error occurs: VM113:1 Uncaught (in promise) SyntaxError: Unexpected end of JSON input at getimag ...

Iterating through a for loop in Angular2 to send multiple GET requests to a Django backend

Currently, I'm facing a challenge with performing multiple GET requests using Angular2 within a Django/Python environment. After successfully making an API request and retrieving a list of users to determine the current user's ID, I utilize a .f ...

communication flow in two directions between server and client

Looking for recommendations on a javascript/nodejs solution that enables bi-directional communication between server and client. The application flow involves the client sending a discovery service to the server, which responds with a challenge. The client ...

Disable the height property in the DOM when implementing the jQueryUI resizable feature

I'm utilizing the flex property to create a responsive layout for my web application. In order to enable resizing of my navigator panel, I have implemented jQuery UI. However, upon triggering the resize event, jQuery UI is adding a hardcoded height t ...

The POST function isn't functioning correctly within the temp.js file

My issue with the post method: var newUser = { "user5" : { "name" : "john", "password" : "qwerty123", "profession" : "developer", "id": 5 } } app.post('/createUser', function (req, res) { // Reading existing use ...

Adding a task to my database successfully through Postman integration

I'm having trouble implementing the code for my todo app using React. I am encountering an issue with adding a new todo to the database using the handleSubmit function. Oddly enough, it works fine when testing with Postman, but not when trying to inpu ...

Creating dynamic links within HTML through real-time updating

In my application, I have a feature that generates a list of words and converts them into clickable links. When the user clicks on a link, I want to extract the {{word.name}} from the HTML link without navigating to a new page. I simply need to retrieve th ...

Comparing NextJs hydration with using the client-side approach

Currently exploring the ins and outs of NextJs to grasp its fundamental features. It is my understanding that by default, NextJs components operate on the server-side and utilize Hydration to enable interactivity shortly after displaying pre-rendered HTML ...