Issue: $parse:syntax Syntax Error

This bug is really frustrating me and I could use some help.

Oops! The Syntax Error: Token '{' is not a valid key at column 2 of the expression [{{ field }}.$error] starting at [{ field }}.$error].

form-input.html

<div class='row form-group' ng-form="{{ field }}" ng-clase="{ '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-messages='required'> {{ field | labelCase }} is necessary. </p>
        <p class='control-label' ng-repeat='(k, v) in types' ng-messages='{{ k }}'> {{ field | labelCase }} {{ v[1] }} </p>
    </div>
</div> 

directives.js

angular.module('ContactsApp')
    .value('FieldTypes', {
        text: ['Text', 'should be text'],
        email: ['Email', 'should be email'],
        number: ['Number', 'should be number'],
        date: ['Date', 'should be date'],
        datetime: ['Datetime', 'should be datetime'],
        time: ['Time', 'should be time'],
        month: ['Month', 'should be month'],
        week: ['Week', 'should be week'],
        url: ['URL', 'should be URL'],
        tel: ['Phone Number', 'should be phone number'],
        color: ['Color', 'should be color']
    })
    .directive('formInput', function ($timeout, FieldTypes) {
        return {
            restrict: 'EA',
            templateUrl: 'views/form-field.html',
            replace: true,
            scope: {
                record: '=',
                field: '@',
                live: '@',
                required: '@'
            },
            link: function ($scope, element, attr) {
                $scope.types = FieldTypes;

                $scope.remove = function (field) {
                    delete $scope.record[field];
                    $scope.blurUpdate();
                };

                $scope.blurUpdate = function () {
                    if ($scope.live !== 'false') {
                        $scope.record.$update(function (updatedRecord) {
                            $scope.record = updatedRecord;
                        });
                    }
                };
                var saveTimeout;
                $scope.update = function () {
                    $timeout.cancel(saveTimeout);
                    saveTimeout = $timeout($scope.blurUpdate, 1000);
                };
            }
        };
    });

list-of-items.html

<p>
    <input type='search' class='form-control' placeholder='Search' ng-model='query'/>
</p>

<table class='table table-hover table-bordered'>
    <thead>
        <tr>
            <th ng-repeat='field in fields' ng-click='sort(field)'>
                {{ field | labelCase }}
                <span ng-show='sort.field === field && !sort.order' class='glyphicon glyphicon-chevron-down'></span>
                <span ng-show='sort.field === field && sort.order' class='glyphicon glyphicon-chevron-up'></span>
            </th>
        </tr>
    </thead>
    <tbody>
        <tr ng-click='show(contact.id)' ng-repeat='contact in contacts | filter: query | orderBy: sort.field : sort.order'>
            <td ng-repeat='field in fields'>
                {{ contact[field][0] }}
            </td>
        </tr>
    </tbody>
</table>

I personally don't see any syntax errors. Any thoughts on why this issue keeps happening?

Answer №1

When evaluating {{ field }}.$error for the first time, Angular does not yet interpolate {{ field }}, so it interprets the first { as the start of an object declaration and the second one as a key. However, after the initial digest cycle, it works correctly once {{ field }} is interpolated to whatever.$error.

There's no need for {{ field }}. Instead, use ng-form="form", replace {{ field }} with form, and remove the parameter from remove(). The actual name of the form object is irrelevant in this context.

Answer №2

Using {{ }} in your html template signals to Angular that it should interpret the enclosed content as an angular expression. Placing this within an existing angular expression will cause a syntax error because it is not valid JavaScript. Any properties starting with ng- are automatically recognized as angular expressions.

<div class='row form-group' ng-form="{{ field }}" ng-clase="{ 'has-error': {{ field }}.$dirty && {{ field }}.$invalid }">

In this case, the contents of ng-clase are already treated as an angular expression, so using {{ }} is redundant. The corrected code should appear as follows:

<div class='row form-group' ng-form="field" ng-class="{ 'has-error': field.$dirty && field.$invalid }">

The error was reproduced in this error-causing jsfiddle and resolved in this fixed jsfiddle.

Edit: Upon investigation, the mistake was actually not caused by the line mentioned earlier. The type mismatch in ng-clase led to the expression being ignored. It seems that the problematic line was:

 <div class='col-sm-4 has-error' ng-show='{{ field }}.$dirty && {{ field }}.$invalid' ng-messages='{{ field }}.$error'>

A similar correction can be applied here:

<div class='col-sm-4 has-error' ng-show='field.$dirty && field.$invalid' ng-messages='field.$error'>

Answer №3

It seems like there may be a piece missing in the puzzle, especially since the directive isn't being instantiated from list.html. This is preventing us from seeing the complete picture.

Additionally, the way {{field}} is utilized in form-field.html appears to be unconventional: the directive is receiving field='@' as a string, but then it's being treated as an object within form-field.html. I recommend referring to the $compile documentation for a clearer understanding of how parameters are passed to the directive's isolated scope.

https://docs.angularjs.org/api/ng/service/$compile

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

What could be the reason behind Next.js attempting to import a non-existent stylesheet?

Lately, I've come across an issue where Nextjs is attempting to import a non-existent stylesheet (refer to the images below). I'm looking for guidance on how to resolve this error. Hoping to find a solution here, thank you Web browser console W ...

Caption image on hover

Is it possible to make an image overlap text on a horizontal menu bar when hovering with the mouse? I am designing a horror website and would like a bloody handprint to appear over the links in the menu bar when they are hovered over. I know this can be do ...

Developing a dynamic table using HTML and JavaScript

I have a question that might sound silly, but I am trying to retrieve the HTML content from this particular website using JavaScript. The data I'm interested in is located at the center of the page within a dynamic table which does not change the URL ...

Inexperienced individual asks: 'Is it possible to accomplish this task using Dojo and Ajax?'

On my website, there is a feature that sends an initial request to a web service. Once this request is sent, the user has to wait for a specific amount of time before being able to send a second request. During this waiting period, I would like a countdo ...

Removing a Div with Dynamic Parameters

I'm struggling to implement a feature in my form that allows the user to add multiple entries, but I'm having trouble with the removal aspect. Here is the JavaScript code: var i = 1; var divContent = document.getElementById ...

Is it possible for my commitment to consistently provide identical values, even when the data varies each time it is invoked?

Initially, the getCart method is invoked in b-navbar.component.ts: export class BNavbarComponent implements OnInit{ appUser: any; cart$ : Observable<ShoppingCart | null>; constructor(private auth : AuthService, private shoppingCartService : S ...

Leveraging Javascript to modify HTML elements generated by a CMS

Our small business decided to partner with Web.com for a year-long contract to create and manage a website with unlimited changes. However, we have encountered limitations with their content management system and lack of technical expertise from their staf ...

Error encountered: The initMap function from the React Google Maps API is not recognized. No relevant

Encountering an issue where initMap is not recognized as a function. I attempted to avoid utilizing any additional packages for asynchronously loading the script or Google Maps API. My initial approach was to simply console log initMap to track when the sc ...

AngularJS issue: Page content not refreshing

Currently, I am in the process of developing a web application that consists of two main pages - home.html and about.html. The issue I am encountering is that when users click on a specific user in the home.html page, they are redirected to about.html bu ...

Variations of a particular software package are necessary

My current project requires Expo, React, and React-Native as dependencies. The configuration in the package.jason file looks like this: "main": "node_modules/expo/AppEntry.js", "private": true, "dependencies": { "expo": "^28.0.0", "expo-three": "^ ...

Using Node.js to pass an HTML variable into a Jade template

I have a JavaScript function in Node.js that queries a database and returns a JSON array to a callback function. The callback function then formats that JSON into a pure HTML table and saves that information to a variable. What would be the optimal metho ...

How can I troubleshoot the 'mdDialog console error' that says 'cannot read property element of null'?

Two of my templates are named Left_template_view_html and center_template_view_html When I click on a md-button in the Left_template_view_html I am attempting to display an mdDialog on the document.body What should I pass into the parent parameter: angu ...

Change the visibility of a div element by leveraging the data-target attribute

Hey there, I have a question about how to use the data-target attribute to set the display of a div. Check out my HTML code below: <div class="page page-current" id="home"> PAGE 1 <a href="#" class="next" data-target="#about">Go to about< ...

Is it possible in Javascript to support an array made up of arrays?

I've been told that arrays of arrays are not allowed in JavaScript. Is this still the case? What about the following object – is it valid? object: { array: [ [0], ['1', '2'] ] } Could someon ...

Displaying Material UI textboxes in multiple columns for dynamically created forms using ReactJs from an array

I am working with an API to retrieve a list of cars, and I have come up with the following code snippet to generate labels and textboxes for editing the car codes. {!carQuery.loading && carDefinitions?.map((car: ICarType, idx: number ...

Unique rewritten text: "Displaying a single Fancybox popup during

My website has a fancybox popup that appears when the page loads. I want the popup to only appear once, so if a user navigates away from the page and then comes back, the popup should not show again. I've heard that I can use a cookie plugin like ht ...

Picking Layers on Google Maps with Three.js

I have incorporated the google-maps-api-threejs-layer library into my project from this source. Now, I am looking to implement a picking feature. Here is the modified code snippet: <!doctype html> <html> <head> <meta charset=&qu ...

Exploring the power of Lingui and yup validation within the NextJS framework

I'm using react-hook-form, yup in NextJS for form validation. I also implemented Lingui for internationalization by following this documentation. How can I set up internationalization in the yup validator that is supported by Lingui? The issue I am e ...

Problem with traversing from parent to children elements using jQuery selectors

<form data-v-c4600f50="" novalidate="novalidate" class="v-form"> <div data-v-c4600f50="" class="pr-2" question="Top Secret4"> <div data-v-c4600f50="" f ...

How to prevent panning on mobile devices in Three.js using Javscript?

Currently working on my 3D project using three.js and everything is running smoothly on my laptop. I'm utilizing OrbitControls for camera movement, but I have disabled right-click panning to only allow camera rotation. However, when testing on a mobil ...