error message when using ng-click and passing arguments is incorrect

I am encountering an issue while adding an object to an array of objects and attempting to delete it using its ID

When utilizing ng-repeat to iterate over the array and display certain elements for each object found, including a button with ng-click="removeWeek({{ key }})", I face a problem. Despite displaying the button correctly with the appropriate key when inspecting the element in the browser, the console throws an error preventing the button from functioning. Strangely, using {{ key }} elsewhere in the ng-repeat does not result in any errors.

Error: [$parse:syntax] http://errors.angularjs.org/1.2.7/$parse/syntax?p0=key&p1=is%20unexpected%2C%20expecting%20%5B%3A%5D&p2=14&p3=removeWeek(%7B%7Bkey%7D%7D)&p4=key%7D%7D)
    at Error (<anonymous>)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js:6:449
    at Xa.throwError (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js:155:346)
    at Xa.consume (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js:156:325)
    at Xa.object (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js:164:6)
    at Xa.primary (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js:154:482)
    at Xa.unary (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js:161:240)
    at Xa.multiplicative (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js:160:480)
    at Xa.additive (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js:160:340)
    at Xa.relational (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js:160:204) <button type="button" ng-click="removeWeek({{key}})"> 

Reviewing the error message on docs.angularjs.org provides further clarification:

Syntax Error: Token 'key' is located at column {2} of the expression [{3}] starting at [{4}].

Below is the HTML code snippet:

<div ng-repeat="(key, week) in program.weeks">

            <input type="text" placeholder="Name the week" ng-model="week.name">
            <input type="text" placeholder="Describe It" ng-model="week.desc">
            {{ week.name }}</br>
            {{ week.desc }}</br>
            {{ key }}
            <button type ="button" ng-click="removeWeek({{key}})"> Remove week</button>
        </div>

The app.js file contains the following functions:

var myModule = angular.module("trainercompare", ['ui.bootstrap']);

function programsController($scope, $http) {

    var numweeks = 1;
    $scope.program = { 

    };

    $scope.addWeek = function() {

        if (isDefined($scope.program.weeks)) {
            $scope.program.weeks.push(
                {
                    days:[]
                }
            );

        } else {
            $scope.program = { 
                weeks: [
                    {
                        days:[]
                    }
                ]
            };
        }
    };

    $scope.removeWeek = function(id) {
        $scope.progmram.weeks[id].remove();
    };

    function isDefined(x) {

    return x !== undefined;
    }

    $scope.addProgram = function() {

        console.log($scope.program);

        $http.post('/programs', $scope.program).success(function(data, status) {
            if(isDefined(data.errors)) {
                console.log(data.errors);
                }
            if(isDefined(data.success)) {
                console.log(data.success);
            }
        });

    }; 


}

Looking for guidance on resolving the error as well as how to properly implement the removeWeek method functionality.

Answer №1

No necessity for enclosing the {{ }} on key.

<button type ="button" ng-click="deleteSection(key)"> Delete section</button>

Answer №2

If you want to pinpoint the position of your object within the array, follow these steps

<button type ="button" ng-click="removeWeek($index)"> Remove week</button>

This will allow you to

<div ng-repeat="week in program.weeks">

    <input type="text" placeholder="Name the week" ng-model="week.name">
    <input type="text" placeholder="Describe It" ng-model="week.desc">
        {{ week.name }}</br>
        {{ week.desc }}</br>
        {{ key }}
    <button type ="button" ng-click="removeWeek($index)"> Remove week</button>
</div>

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

Error: Unable to locate sportsRecord due to missing function

updated answer1: Greetings, I have updated the question with some detailed records and console logs for better understanding. sportsRecord = { playerTigers:[ {TigerNo: 237, TigerName: "Bird Bay Area", TigerkGroupNo: 1, isDefault: true ...

What are the steps for transitioning an Angular application from MonoRepo to PolyRepo?

Having created three separate Angular applications with individual workspaces, projects, and repositories, I am able to share modules among them using @angular-architects/module-federation. However, I am facing challenges when it comes to sharing component ...

Can routes be nested in React components?

I'm curious to know if there's a way to integrate nested routes in React, where the Navbar component serves as the parent for dashboard and properties. <Router> <Routes> <Route path='/' element={<Home />} /> ...

What methods can be used to ensure a required minimum delay time between function executions?

For my node function, I am aiming for a specific execution delay of around 5 seconds. The minimum delay needs to be implemented within the function itself, not externally, so external users are unaware of the delay. Therefore, I cannot rely on modules l ...

When iterating through a JavaScript object, opt for utilizing references instead of repeatedly specifying the path

for (var element in array[index1][index2][index3].property) { alert(array[index1][index2][index3].property[element].data); } Is there a more succinct way to achieve the same result by referencing the object directly like this: for (var ...

Is there a way to generate an array from 1 to X without using a loop?

What is a way to generate a JavaScript array from 1 to X without using a loop when the value of X is only known at runtime? var arr = []; for (var i = 1; i <= x; i++) { arr.push(i); } ...

Storing email addresses in variables and sending them using node.js

const functions = require('firebase-functions'); var nodemailer = require('nodemailer'); var transporter=nodemailer.createTransport('smtps://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dca9afb9aeb2b ...

Experience the power of TypeScript in a serverless environment as you transform your code from

I have some JavaScript code that needs to be converted to TypeScript. Currently, I have two files: API_Responses.js const Responses = { _200(data = {}) { return { statusCode: 200, body: JSON.stringify(data), }; } }; module.export ...

Error: Koa.js framework is unable to find the "users" relation in the Sequelize database

I am currently facing an issue while attempting to establish a relationship between two tables, 'user' and 'accessToken'. The error message I am encountering is hindering the process. Below are the models in question:- User model:- ...

Linking Google Form Data to a MongoDB Database

Looking to integrate Google form with mongodb for data collection. Need help setting it up using NodeJs. Any advice on how to approach this? ...

Combine large arrays

Hey, I'm encountering some issues while trying to merge large arrays in a React Native app. Specifically, I am attempting to implement infinite scroll on React Native. The issue arises when the array reaches 500+ items; every time I add more items, my ...

What's the best way to retrieve the dates for the current week using JavaScript?

Could anyone help me find a way to retrieve the first and last dates of the current week? For example, for this week, it would be from September 4th to September 10th. I encountered an issue at the end of the month when dates overlap two months (such as t ...

Trouble with transmitting props to function

The child component is not receiving the props as expected. When printed, it displays an empty object. The problem seems to be in the News.js file specifically related to passing props to the child component from App.js. All functions are operational excep ...

Cannot confirm checkbox status in ASP.NET after retrieving data from webmethod using Jquery AJAX

Implementing Jquery ajax to call a webmethod, the webmethod interacts with the database and returns either true or false. The goal is to determine whether the checkbox should be checked or unchecked based on this boolean value. Here is the server-side cod ...

Store data in Firebase Storage and retrieve the link to include it in Realtime Database

Utilizing Firebase Realtime Database and Firebase Storage for this application involves uploading images from the pictures array to Firebase Storage. The goal is to obtain the Firebase Storage link for each image, add it to the object pushed into imagesU ...

Request for an Ajax web service

I have recently gained access to a new web service that returns data in XML format. While working with this service, I encountered two types of errors: the Cross-Origin Domain Error and a new error message stating "refuse to execute script from because its ...

Is there a way to find the TextArea element on Facebook's home page using a Selenium locator? Could it possibly be using jQuery

Sign in using any of our Facebook login details. Upon successful login, you will be directed to the page below. Query: Can you spot the "What's on your mind" or "continue to post" text box? I need to find the text box, input text, and then click on ...

Filter out specific fields from an object when populating in MongoDB using the aggregate method

Is there a way to use the populate() function in MongoDB to exclude specific fields like email and address, and only retrieve the name? For example: const results = await Seller.aggregate(aggregatePipeline).exec(); const sellers = await Seller.populate(re ...

Wrap all temporary array elements of the same type within an object

Extracted from a json api, the following snippet of content showcases various titles and content types: contents: [ { title: "some title", content_type: 2 }, { title: "some title", content_type: 2 }, { title: "some title", content_type: 1 }, { title: ...

Ways to extract metadata from a given URL

Recently, I've delved into the world of JavaScript and I'm looking to extract metadata from a given URL. Whenever a URL is entered into an input field, I want to retrieve its meta data - a simple task in HTML using JavaScript. However, every time ...