Receiving the error message "Encountered SyntaxError: Unexpected token )" when using a custom directive

Encountering an issue with the customer directive of auto-complete, as I am receiving the error

Uncaught SyntaxError: Unexpected token )
. This error is displayed in the console of the chrome browser as
VM80623:1 Uncaught SyntaxError: Unexpected token )
. Clicking on VM80623:1 leads to void(); in File name VM80623

The same error persists even when implementing the directive from the following link where you can type any character, use the auto-complete search box, and select an option.

Link:

(function () {
    'use strict';
    var app = angular.module('app');
    app.directive('Autocomplete', ['Authentication', '$http', function(AuthenticationService, $http){
        return {
            restrict : 'AEC',
            require: 'ngModel',
            scope: {
              modeldisplay:'= modeldisplay'
            },
            templateUrl: 'directives/autocomplete/autocomplete.html',
            link: function(scope, element, attrs, ctrl){
              scope.searchCustomer = function(customerSearch){
                  var params = {
                    'session_key': Authentication.GetSessionKey(),
                    'q': customerSearch
                  };
                  if (!customerSearch){
                    return;
                  }
                  var url = config.url+'/api/search';
                  return $http.post(url, params).then(function(response){
                        var data = response.data;
                        if(data.error == 0) {
                          scope.TypeAheadData = data.result;
                          return data.result;
                        }
                      });
              }
              scope.handleSelection = function(item){
                ctrl.$setViewValue(item);
                scope.modeldisplay = item;
                scope.selected = true;
              };
              scope.isCurrent = function(index) {
                return scope.current == index;
              };
              scope.setCurrent = function(index) {
                scope.current = index;
              };
            }
          };
      }]);
  })();

Answer №1

These are the issues found in the code:

  1. scope: { modeldisplay:'= modeldisplay', // there is an extra comma that should be removed }

  2. var url = config.url'/api/search' // config.url and '/api/search' need to be concatenated

Here is the corrected code:

 (function () {
    'use strict';
    var app = angular.module('app');
    app.directive('Autocomplete', ['Authentication', '$http', function(AuthenticationService, $http){
        return {
            restrict : 'AEC',
            require: 'ngModel',
            scope: {
              modeldisplay:'= modeldisplay'
            },
            templateUrl: 'directives/autocomplete/autocomplete.html',
            link: function(scope, element, attrs, ctrl){
              scope.searchCustomer = function(customerSearch){
                  var params = {
                    'session_key': Authentication.GetSessionKey(),
                    'q': customerSearch
                  };
                  if (!customerSearch){
                    return;
                  }
                  var url = config.url + '/api/search';
                  return $http.post(url, params).then(function(response){
                        var data = response.data;
                        if(data.error == 0) {
                          scope.TypeAheadData = data.result;
                          return data.result;
                        }
                        else {
                          return;
                        }
                      });
              }
              scope.handleSelection = function(item){
                ctrl.$setViewValue(item);
                scope.modeldisplay = item;
                scope.selected = true;
              };
              scope.isCurrent = function(index) {
                return scope.current == index;
              };
              scope.setCurrent = function(index) {
                scope.current = index;
              };
            },
          };
      }]);
  })();

Answer №2

After importing your code into IntelliJ, I noticed an issue with this line:

var url = config.url'/api/search';

To fix this problem, you need to concatenate the variable and the string like this:

var url = config.url + '/api/search';

There are a few other minor syntax errors in the code, but they should not prevent it from running.

In the following snippet:

scope: {
  modeldisplay:'= modeldisplay',
},

The comma at the end is unnecessary:

scope: {
  modeldisplay:'= modeldisplay'
},

Make sure to add a semicolon at the end of the searchCustomer method:

scope.searchCustomer = function(customerSearch){
  // other code here
};

Also, remove the comma at the end of the link function:

            } // remove comma here,
        };
    }]);
})();

Lastly, IntelliJ flagged the else return statement in the $http.post result function:

                    return $http.post(url, params).then(function(response){
                        var data = response.data;
                        if(data.error == 0) {
                            scope.TypeAheadData = data.result;
                            return data.result;
                        }
/* not needed because we are at end of method 
                       else {
                            return;
                        } */
                    });

Here is the updated code with all the corrections applied:

(function () {
    'use strict';
    var app = angular.module('app');
    app.directive('Autocomplete', ['Authentication', '$http', function(AuthenticationService, $http){
        return {
            restrict : 'AEC',
            require: 'ngModel',
            scope: {
                modeldisplay:'= modeldisplay'
            },
            templateUrl: 'directives/autocomplete/autocomplete.html',
            link: function(scope, element, attrs, ctrl){
                scope.searchCustomer = function(customerSearch){
                    var params = {
                        'session_key': Authentication.GetSessionKey(),
                        'q': customerSearch
                    };
                    if (!customerSearch){
                        return;
                    }
                    var url = config.url + '/api/search';
                    return $http.post(url, params).then(function(response){
                        var data = response.data;
                        if(data.error == 0) {
                            scope.TypeAheadData = data.result;
                            return data.result;
                        }
/*                        else {
                            return;
                        } */
                    });
                };
                scope.handleSelection = function(item){
                    ctrl.$setViewValue(item);
                    scope.modeldisplay = item;
                    scope.selected = true;
                };
                scope.isCurrent = function(index) {
                    return scope.current == index;
                };
                scope.setCurrent = function(index) {
                    scope.current = index;
                };
            }
        };
    }]);
})();

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

How can I transfer an instance of a class to dataTransfer.setData?

So I created a new instance of a class: let item = new Item(); Next, I attempted to serialize the item and add it to dataTransfer for drag and drop functionality: ev.dataTransfer.setData("info", JSON.stringify(item)); At some point, I need to retriev ...

Can you send JSON data and redirect simultaneously using Express?

In my application, there is a registration feature that involves sending a confirmation email to the user. I am looking to achieve a similar outcome as shown below: return res.status(200).redirect('/').json({ message: 'Successfully confir ...

Take the user input from the form and incorporate it into the URL for the AJAX request

How can I dynamically update the URL in the AJAX call asynchronously? I've made a few attempts, but none of them seem to work. This is the current code: <!-- Input form --> <form class="navbar-form navbar-left" role="search" id="formversion" ...

Begin anew with Flip.js

Currently, I am incorporating the jquery flip plugin from nnattawat.github.io/flip to establish a card flipping mechanism on my website. I have successfully implemented the method outlined in the documentation to unregister the flip event from the elemen ...

Is there a way to efficiently retrieve multiple values from an array and update data in a specific column using matching IDs?

In my Event Scheduler spreadsheet, I am looking for a way to efficiently manage adding or removing employees from the query table in column A. Currently, I have a dropdown list in each row to select names and a script that can only replace one name at a ...

The NoUiSlider had already been initialized

Currently, I am facing an issue when trying to incorporate noUiSlider with Angular JS. I have a directive that contains 4 sliders and I intend to display this directive on 2 different pages. However, each time I switch between the pages, an error occurs st ...

Leverage the Power of AngularJS to Harness Local

I am currently developing an application using AngularJS. However, I have encountered an issue when trying to use localstorage. Here is my code snippet: var id = response.data[0].id; var email = response.data[0].email; localStorage.setItem('userId&ap ...

Struggling to connect CSS and JavaScript files to index.html on Heroku while utilizing Node.js

Trying to set up a Tic Tac Toe game in my app.js file, but encountering some issues with linking files in index.html. app.set('port', (process.env.PORT || 5000)) //serve static files in the public directory app.use(express.static('public& ...

Understanding the default value type in React's setState method

I am new to React and facing difficulties identifying errors in my code. My goal is to display a list of users retrieved from a server using socket.io. Below is the original code snippet: // list of users const [users, setUsers] = useState() useEffect(() ...

A guide on how to automatically preselect a RadioGroup option in Material-UI

When a user selects an option from the MCQ Select using RadioGroup in my code and submits it, they should be able to return later and see the option they selected highlighted, similar to how Google Forms allows users to review their selections. Below is t ...

Tips on aligning a div to the right of a headline

My goal is to have an orange circle image placed to the right of my headline <h2>. However, I am facing an issue where the circle jumps above the headline when I shrink the screen. How can I ensure that it stays on the right side no matter the screen ...

Ways to consistently press a particular button every single second

The code on the webpage looks like this: <div id="content"> <div class="container-fluid"> Slots <p>The current jackpot is 23220!<p/> <p>You lose.</p> <form method=post action=/game ...

Mastering AngularJS Authentication: A Step-by-Step Guide for the First Submission

I have a login function in Angularjs, but it only works when I submit it for the second time. How can I fix this issue? Here is my code: .controller('LoginCtrl', ['$scope', '$rootScope', '$location', 'Authenti ...

Having difficulty aligning ListItem to the right within a List

I am working with an array that contains objects which I need to display in ListItems of a List. My goal is to show these ListItems from the array Objects in a layout where odd numbers are on the left and even numbers are on the right. However, I am facing ...

Deselect the checkbox that was initially selected when an alternative checkbox option has been chosen

I am trying to implement a feature where there are 2 groups of checkbox options on the same page. Below is the code snippet: <div class="col-xs-12"> <label class="checkbox-inline"> <input type="checkbox" th:field="*{borrowerRace1}" th:val ...

Incorporate a map (using leafletjs or Google Maps) as a subtle backdrop

I am currently working on a one-page website and I would like to include a map as a background behind the "contact" section. The map can be set to float, draggable, or positioned at the back. I have experience using both the Google Maps API and LeafletJS, ...

Refresh the Rails HTML table with new data by incorporating ajax requests and vanilla JavaScript

I'm struggling to find a solution without using jQuery in my current scenario. How can I refresh a partial on my page without reloading the entire page? Within my new.html.erb file, there's a button that triggers a JavaScript function each time ...

Utilizing the combineReducers() function yields disparate runtime outcomes compared to using a single reducer

Trying to set up a basic store using a root reducer and initial state. The root reducer is as follows: import Entity from "../api/Entity"; import { UPDATE_GROUPING } from "../constants/action-types"; import IAction from "../interfaces/IAction"; import IS ...

Oops! An issue has occurred where I am unable to access certain properties (specifically 'Symbol(__APOLLO_CONTEXT__)') while utilizing the Apollo provider

When attempting to implement a query in my upcoming app, I encountered an error that reads: Error: Cannot read properties of undefined (reading 'Symbol(APOLLO_CONTEXT)') This is the setup of my Apollo client: import { ApolloClient, InMemoryCache ...

Is there a way to retrieve files stored on my hard drive within a webpage?

I have a large number of files stored on my hard drive, all following the same format, 2014.C1.012.012 - full name of the file. They each have unique numbers and names. I want to create a local webpage where I can organize these files into a table w ...