Struggling to troubleshoot an error - Invalid key Token '{' found at column 2

I am encountering a debugging issue that I can't seem to resolve.

form-field.html

<div class='row form-group' ng-form="{{field}}" ng-class="{ 'has-error': {{field}}.$dirty && {{field}}.$invalid }">
    <label class='col-sm-2 control-label'> {{ field | labelCase }} <span ng-if='required'>*</span></label>
    <div class='col-sm-6' ng-switch='required'>

        <input ng-switch-when='true' ng-model='record[field][0]' type='{{record[field][1]}}' class='form-control' required ng-change='update()' ng-blur='blurUpdate()' />

        <div class='input-group' ng-switch-default>
            <input ng-model='record[field][0]' type='{{record[field][1]}}' class='form-control' ng-change='update()' ng-blur='blurUpdate()' />
            <span class='input-group-btn'>
                <button class='btn btn-default' ng-click='remove(field)'><span class='glyphicon glyphicon-remove-circle'></span></button> 
            </span>
        </div>
    </div>

    <div class='col-sm-4 has-error' ng-show='{{field}}.$dirty && {{field}}.$invalid' ng-messages='{{field}}.$error'>
        <p class='control-label' ng-message='required'> {{ field | labelCase }} is required. </p>
        <p class='control-label' ng-repeat='(k, v) in types' ng-message='{{k}}'> {{ field | labelCase }} {{v[1]}}</p>
    </div>
</div>

new.html

<h2> Add New Contact </h2>

<form name='newContact' novalidate class='form-horizontal'>
    <form-field record='contact' field='firstName' live='false' required='true'></form-field>



 <div class='row form-group'>
        <div class='col-sm-offset-2'>
            <button class='btn btn-primary' ng-click='save()'> Create Contact </button>
        </div>
    </div>
</form>

I'm currently facing the following error:

On the browser:

Error: [$parse:syntax] http://errors.angularjs.org/1.4.1/$parse/syntax?p0=%7B&p1=invalid%20key&p2=2&p3=%7B%7Bfield%7D%7D.%24error&p4=%7Bfield%7D%7D.%24error

Reported on angular site:

Error: $parse:syntax Syntax Error Syntax Error: Token '{' invalid key at column 2 of the expression [{{field}}.$error] starting at [{field}}.$error].

Any insights into why this might be happening would be greatly appreciated! Thanks!

Answer №1

Upon observation, I have also encountered this issue when trying to bind data to an attribute within a custom directive. Here is an example:

$scope.customData.value = "Goodbye!";

The following snippet results in an error:

<my-custom-directive my-attribute="{{customData.value}}"></my-custom-directive>

However, the below code functions correctly:

<my-custom-directive my-attribute="customData.value"></my-custom-directive>

Answer №2

The issue lies in your code:

ng-class="{ 'has-error': {{field}}.$dirty && {{field}}.$invalid }"

To correct it, remove {{ }}:

ng-class="{ 'has-error': field.$dirty && field.$invalid }"

You'll also encounter a similar problem here:

ng-messages='{{field}}.$error'

Replace it with:

ng-messages='field.$error'

However, rectifying these may lead to an error in this line:

ng-message='{{k}}'

Therefore, modify it to:

ng-message='k'

Answer №3

During my experience following a tutorial, I encountered a similar issue. Upon investigation, I realized that the problem stemmed from using a newer version of ngMessages compared to what was demonstrated in the tutorial. To resolve this, I updated my bower.json file to match the version used in the tutorial videos. This fixed the issue, and below is the section of my dependencies detailing the changes:

"dependencies": {
  "angular": "1.3.9",   
  "angular-route": "1.3.9", 
  "angular-resource": "1.3.9", 
  "angular-messages": "1.3.9", 
  "bootstrap": "^3.3.6"}

Answer №4

Imagine this as my own HTML markup

<div ng-controller='MyCtrl' ng-init="array=[{id:1}, {id:2}]">Hey there, it's {{name}}. 
      <div ng-repeat='obj in array'>
        The current time is <display-time data="{{array}}"/>.
      </div>
</div>

In the code above, display-time represents a custom directive defined below

var demo = angular.module('demo', []);
demo.directive('displayTime', function($parse) {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            data: '='
        },
        transclude: false,
        template: '<span class="currentTime"></span>',
        link: function (scope, element, attrs, controller) {
            var currentDate = new Date();
            console.log(scope.data);
            element.text(currentDate.toTimeString());
        }
    }});

Pay attention to the usage of data="{{array}}".

When I include data in the scope of the custom directive with

scope: {
    data: '='
},

I encounter a parse error.

However, by changing the syntax to data="array" and updating the following snippet within the link function

scope: {
    //data: '='
},

I can avoid a parse error.

Therefore, stick to using data="{{array}}" only if intending to access it through attrs parameter inside the link function.

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

Angular: Utilizing Nested ng-repeat Alongside groupBy Feature on Initial Page Load or Refresh

With some help, I've made it this far on my project. However, I need to take one more step to achieve my goal. I want to group data based on an attribute that is currently passed through an ng-click action. Is there a way to automatically do this on p ...

What could be causing the element.style.FontSize to not be effective on classes that have been looped through and stored in an array created with querySelectorAll beforehand?

Greetings Stackoverflow Community, Today, I'm facing an issue related to JavaScript and WordPress. I have a JavaScript script named setDynamicFontHeight.js, as well as PHP documents named header.php and navbar_mobile.php, which simply executes wp_nav_ ...

Saving changes made in HTML is not supported when a checkbox is selected and the page is navigated in a React application using Bootstrap

In my array, there are multiple "question" elements with a similar structure like this: <><div className="row"><div className="col-12 col-md-9 col-lg-10 col-xl-10 col-xxl-10"><span>Question 1</span></div ...

Displaying JavaScript array contents in an HTML page without using the .innerHTML property

As someone new to the world of JavaScript and web development, I find myself faced with a challenge. I want to showcase the contents of two different JavaScript arrays in an HTML format. However, my research has led me to believe that utilizing .innerHTML ...

Why won't my dropdown menu work properly with JavaScript on certain pages?

Being new to javascript, I encountered an issue with a function that I recently modified. When a user selects "Yes" from a dropdown menu, it should generate 3 text boxes within a specific div area. Below is the code for my form dropdown: <select name= ...

Tips for updating the left positioning of a Div element on the fly

Although my title may not fully explain my goal, I am dealing with dynamically created div elements. When a user triggers an ajax request to delete one of the divs, I want to remove it from the DOM upon success. The issue arises in adjusting the layout aft ...

Modify the readonly property of an input element in ReactJS

I am looking to manipulate attributes on an HTML input element. Here is what I have attempted: constructor(props) { super(props); this.state = {inputState: 'readOnly'}; } And within the render function: <input className="form-contr ...

Unable to transform data types

Currently, I am studying the JavaScript for automation session at WWDC. Here is an example taken from slide 99 that I am working on. On a fresh installation of Yosemite, I encountered an error on line 3. Safari = Application('Safari') doc = Safa ...

Easy Registration Page using HTML, CSS, and JavaScript

In the process of creating a basic login form using HTML and CSS, I'm incorporating Javascript to handle empty field validations. To view my current progress, you can find my code on jsfiddle My goal is to implement validation for empty text fields ...

Retrieving data from external JSON files

I implemented this JavaScript code to retrieve JSON data from an external server. The JSON data gets loaded from the server, but I'm unsure how to extract markers from the Google Map using this external JSON data. var map, infowindow; //// // Fet ...

What is the best way to retrieve information from a data set?

After borrowing some basic HTML, CSS, and JavaScript code from CodePen, I ran into an issue while attempting to convert it to React. The error message says that it cannot read properties of null (specifically 'dataset'). Here is the JavaScript c ...

Tips for accessing the URL in PhoneGap and parsing the response with jQuery

Currently, I am working on a task in PhoneGap which involves creating a registration page. When the user clicks on the registration page, the values entered will be sent to a specific URL. If the user is already registered or not, the data will be returned ...

Ways to remove the address bar from a mobile browser like Chrome or an Android browser

Is there a way to make videojs go full screen on Android devices when the URL is entered, without displaying the address bar? ...

Performing optimized searches in Redis

In the process of creating a wallet app, I have incorporated redis for storing the current wallet balance of each user. Recently, I was tasked with finding a method to retrieve the total sum of all users' balances within the application. Since this in ...

What is the best way to create direct links to tabs using #anchors in JavaScript?

I am managing a website that includes info-tabs based on a template I found at this link. The tabs contain anchors like example.com/#convey, but unfortunately, direct links to specific tabs using #anchor do not work properly due to the tabs relying on Java ...

What is the best way to eliminate the final character from a series of repeated Xs and following strings

Data consists of [one][two][three]. I want to exclude the last set of brackets and have a result like [one][two]. How can this be achieved using jQuery? ...

Submitting both $_POST[] data and $_FILES[] in a single AJAX request

Struggling with uploading images along with dates on my website. I am passing the date using $_POST and the image files in $_FILES. Here is the Javascript code snippet: (function post_image_content() { var input = document.getElementById("images"), ...

I'm encountering some puzzling errors from the Codacy feature in GitHub that are leaving me completely baffled

I'm currently using Codacy in my code repository to assess the quality of my work. Struggling with two errors during commit, unsure how to troubleshoot them. Can anyone offer assistance? Issue: Expected property shorthand. Error occurs in this line ...

"There is an issue with the payload size: request entity is too large. What is the solution for handling this in Nest

I am facing an issue where I need to send a request containing a large base64 string, approximately around 2 MB. However, the server keeps throwing an error message. How can I prevent this error from occurring: [Nest] 1666 - 11/01/2021, 1:50:58 PM ERRO ...

Python and Javascript clashing with one another

(Updated question for clarity). I am currently developing a flask app game that involves users inputting guesses via the web browser. The backend, which runs on Python, checks these guesses and provides feedback to the user about their accuracy. Additional ...