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

When checking if el.text() is equal to "string", it will return false, regardless of the actual content of the element being "string"

Looking at the code snippet below, it seems that the else block is always being executed instead of the if block. The alert confirms that the variable state has the value 'payment' as expected. var state = $('.check-state').text(); ale ...

Application utilizing electron technology featuring various tabbed browsing windows connecting to secure websites

Currently, I am in the process of developing my own unique version of a platform similar to using Electron technology. The objective for this app is to provide users with the ability to view multiple URLs simultaneously, such as and , through a tabbed i ...

The distinction between a keypress event and a click event

Due to my eyesight challenges, I am focusing on keyboard events for this question. When I set up a click event handler for a button like this: $("#button").on("click", function() { alert("clicked"); }); Since using the mouse is not an option for me, ...

Vue - making one element's width match another element's width

Trying to dynamically adjust the innermost element's width to match the outermost element's width with Vue: <div id="banner-container" class="row"> <div class="col-xs-12"> <div class="card mb-2"> <div ...

I can't seem to figure out why my attempts to set a cookie through Express are failing

I am currently facing an issue with sending a cookie back to my React app after logging in. In my server, I have set up a test response: res.status(200).cookie('nameOfCookie', 'cookieValue', { maxAge: 1000* 60 * 60 }).end(); In the app ...

Issue with XMLHttpRequest.send() not working in Google Chrome when using POST requests

I'm currently developing an application where users can send files using a form through a POST request. As the file uploads, the application makes multiple GET requests to gather information about the upload progress. Interestingly, this functionalit ...

Identifying and detecting Label IDs when clicked using the for tag

I am facing an issue with labels and input fields in my code. I have multiple labels that trigger the same input field, but I want to know which specific label triggered the input field. <label id="label1" for="input1">Document1</label> <la ...

Extract keys from the string

Is there a better way to extract keys from a string? const {Builder, By, Key, until} = require('selenium-webdriver'); ... const obj = {val: 'Key.SPACE'} if(obj.val.startsWith('Key.'))obj.val = eval(obj.val); (...).sendKeys(obj ...

Is there a way to adjust the label elevation for a Material UI TextField component?

I am trying to enhance the appearance of a textfield label, but I am facing some challenges with my code. textStyle: { backgroundColor: '#1c1a1a', border: 0, borderRadius: 0, width: 400, height: 66, display: 'flex&a ...

Performance of obtaining image data

Is anyone else experiencing a significant lag when trying to retrieve the state of a single pixel on the canvas? Take a look at my JS code below: var state = ctx.getImageData(x,y,1,1).data; state = 'rgba(' + state[0] + ',' + state[1] ...

Learn the best way to populate Google Map popup windows with multiple values and include a button to pass unique ID values

I'm facing an issue with my code. When I click on a marker, it should display "Madivala, 12.914494, 77.560381,car,as12" along with a button to pass ID values. Can someone help me figure out how to move forward? http://jsfiddle.net/cLADs/123/ <ht ...

Identifying tick markers in the event loop of JavaScript and Node.js

Is there a way to determine if a function is called in the current tick or if it will be called in the next tick of Node.js event loop? For instance: function exampleFunction(callback){ // we can call callback synchronously callback(); // or we c ...

What is the best way to create a clickable background for a modal window?

I am looking to add a chatbox feature to my website and have been utilizing Bootstrap Modal for this purpose. My goal is to keep the modal open even when the user clicks outside of it, while still allowing them to interact with the background of the websi ...

The current status of the Macrotask and Microtask queues as this calculation is being processed

This particular inquiry delves into a nuanced aspect of the event loop, seeking clarification through a concrete example. While it shares similar characteristics with another question on Stack Overflow, specifically Difference between microtask and macrota ...

There seems to be an issue with the AJAX REST call failing to transmit data

Whenever I attempt to submit the form, the page refreshes and nothing gets saved in the database. The code in subforum.js $(document).on('click','#submit',function(e) { var user = JSON.parse(sessionStorage.getItem("ulogovan")); consol ...

The jQuery ajax request was unsuccessful in connecting to the remote server

I've tried researching and troubleshooting, but I still can't figure out why the Ajax code is not functioning correctly. Here is my JavaScript code: $(document).ready(function(){ $("#tform").submit(function() { var varUserName ...

What is the best method for tracking the execution time of functions in Node.js?

My nodejs application has numerous functions that need to be executed. I am looking for a way to log the time taken to execute each function. For example, when my app runs these functions: execfn1(); -> should output in some log, takes: 1ms.. execfn ...

What is the best way to navigate users to a different page using AJAX upon receiving a successful response from PHP?

I am currently using a JavaScript function that is functioning correctly. It retrieves all error messages from the PHP file and displays them in a span with the ID "resto" without any issues. However, I now have a requirement where if the PHP file return ...

To effectively utilize the expect function in testing, should you use it over softAssertAll or find a way to explicitly display in the test results that the softAssertAll has successfully passed? (Error

Utilizing the 'soft-assert' library (soft-assert library) allows me to implement assertions in my test steps without halting the entire test if any of them fail. While softAssertAll() command works effectively to verify all soft-assert at the en ...

Instructions on how to activate scrolling for a div element that becomes visible upon clicking a button

When a button in the navbar is clicked, a div appears with a height that exceeds the viewport/page size. How can I enable scrolling for the entire page when this happens? I attempted to use overflow: scroll, but it only applied scrolling to the internal d ...