"Encountering a syntax error with _.map and _.zip in JavaScript

When attempting to use underscore.js with the following code:

(_.map(_.zip([v,xs]),function(rs){return {a:rs[0],x:rs[1]}}))

I encountered a syntax error

The syntax error observed is: Token '{' is unexpected, expecting [)] at column 34 of the expression [(.map(.zip([v,xs]),function(rs){return {a:rs[0],x:rs[1]}}))] starting at [{return {a:rs[0],x:rs[1]}})).

Additional context:

<rect  ng-repeat="z in (_.map(_.zip([v,xs]),function(rs){return {a:rs[0],x:rs[1]}}))" x="{{z.x.x(z.a)}}%" y="{{z.y.y(z.a)}}"  width="{{z.x.w(z.a)}}" height="{{z.x.h(z.a)}}" style="fill:rgba({{z.x.s.r}},{{z.x.s.g}},{{z.x.s.b}},{z.x.s.a}})"/>

Answer №1

Avoid using these techniques within an Angular binding. Instead, consider incorporating them into your controller to handle data processing and utilize ng-repeat for iterating through the modified data. Alternatively, create Angular filters to encapsulate the techniques, especially if they are frequently used.

Answer №2

angular
  .module('app', [])
  .controller('lodashUsageController', lodashUsageController);

function lodashUsageController($scope) {
  $scope._ = _;
  $scope.list = [1, 2, 3, 4, 5, 6];
  $scope.even = function(item) {
    return {
      val: item,
      isEven: item % 2 === 0
    };
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>

<div ng-app="app">
  <div ng-controller="lodashUsageController">
    <ul>
      <li ng-repeat="item in _.map(list, even) track by $index">
        {{item.val}} - {{item.isEven}}
      </li>
    </ul>
  </div>
</div>

As mentioned by Jon Snow, using lodash functions directly within ng-repeat is not recommended.

However, there is a workaround. A jsbin example has been created to demonstrate this.

To make lodash accessible for angular binding, you need to expose "_" as a $scope variable.

$scope._ = _;

Instead of having direct anonymous functions within the binding, create them in the controller and then access them from ng-repeat.

HTML

<div ng-controller="lodashUsageController">
<ul>
  <li ng-repeat="item in _.map(list, even) track by $index">
    {{item}}
  </li>
</div>

JavaScript

function lodashUsageController($scope) {
  $scope._ = _;
  $scope.list = [1, 2, 3, 4, 5, 6];
  $scope.even = function(item) {
    return item % 2 === 0;
  }
}

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

Fixing issues with Ajax calls in Internet Explorer versions 7 and 8

Here is the Javascript code I have written: $("#login").click(function(){ username=$("#user_name").val(); password=$("#password").val(); $.ajax({ type: "POST", url: "login.php", data: "username="+username+"&passw ...

Sending parameters to a service's factory

Here is the HTML code I am working with: <div class='container-fluid' ng-controller="TypeaheadCtrl"> <p></p> <b>Selected User</b> Enter a name: <input type="text" ng-model="selected" typeahead="user ...

Integrate incoming websocket information with state management in React

I am facing a challenge in creating a timeseries plot with data obtained from a websocket connection. The issue arises when new values overwrite the previously stored value in the state variable. const [chartData, setChartData] = React.useState(null) Cu ...

Tips for increasing a variable by one with each button click?

I have a simple JavaScript function called plusOne() that is designed to increment a variable by 1 each time a button is clicked, and then display the updated value on a webpage. However, I'm encountering an issue where the addition only occurs once. ...

Utilizing React Hooks to insert components into a div

I am in the process of creating a todo list using React and realized that states are used in React instead of innerHTML or appendChild() in JavaScript. My challenge lies here: When a user clicks on a button, a simple todo should be added to the parent div ...

Running a website on a virtual server

I am working on a webpage that presents results from an angular application, and I want to host it on a web server located on my virtual machine. This will allow my team members to easily access the page daily. However, I am unsure of how to proceed with ...

Incorporating an array attribute into a current array of elements

I am currently attempting to incorporate the days of the week into an existing array of objects. To give you a visual representation, check out this image: https://i.stack.imgur.com/0jCBF.png After filtering my array to only yield 7 results, I aim to assi ...

Using a promise instead of resolving it with Angular's $q.then() methodology

Imagine you come across the given code snippet: var callNo1 = $http(...).then(function (response1) { var callNo2 = $http(...).then(function (response2) { return [response1.data, response2.data]; }); return callNo2; }).then(function (r ...

The functionality of the .toggle method is limited to only being effective 1.5

I'm having an issue with making an image popup using the .toggle function in javascript. It seems to work initially, but then only works partially after that. When I click on the image, it opens as expected. However, when I try to close it by clickin ...

Avoid displaying duplicate items from the array

Utilizing react js, I am attempting to iterate through an array of objects and display the name of each object in the array: const arr = [ { name:"Bill", age:88 }, { name:"Bill", age:18 }, { name:"Jack", age:55 }, ] ...

Condense categories

Hello there, I'm currently working on a table that contains different groups, and I am trying to figure out how to collapse categories within my table. Check out the Plunker here This is the HTML code snippet I am using: <table border=1> ...

What is the best way to implement two for loops in a Django template to handle sending and receiving chat messages efficiently?

I am attempting to implement sending and receiving messages in a Django template using a for loop. Here is my views function: @login_required def message_form(request, id, slug, user_id): user2 = request.user user_id = user_id user = get_objec ...

Utilizing AJAX in Wordpress to Dynamically Update HREF Links

My website now has AJAX functionality, and you can see a live example at www.mathewhood.com. I am interested in changing the URL format when clicked from To something like , without the /sitefiles/ for security reasons. Below is my code. If anyone is ex ...

Internet Explorer experiencing issues with window resizing event

One common issue with Internet Explorer is that the window.resize event is triggered whenever any element on the page is resized. It doesn't matter how the element's size changes, whether it's through height or style attribute modification, ...

Restarting a JavaScript function upon switching views in Vue.js

I am new to working with Vue.js and I have a Laravel app that utilizes it. One issue I am facing is that when the homepage is loading, all elements like owl carousel and rev slider are initialized. However, if I navigate to other routes such as contact or ...

Tips for automatically closing a dropdown menu when it loses focus

I'm having some trouble with my Tailwind CSS and jQuery setup. After trying a few different things, I can't seem to get it working quite right. In the code below, you'll see that I have placed a focusout event on the outer div containing th ...

How can I bind an event for changing innerHTML in Angular 2?

Is there a way to implement something similar to this: <div [innerHTML]="content" (innerHTMLchange)="contentInit()"></div> Currently, I have a variable content that is updated by a service fetching a string from my express server. The content ...

There was a TypeError encountered in angular-highcharts, stating that it is not possible to read the property '0' of an undefined

Currently, I am utilizing the angular5 framework in conjunction with the angular-highcharts library to generate a basic map based on the highcharts demonstration available at https://www.highcharts.com/maps/demo/category-map. Here is a snippet of the code: ...

Error TS2307: Module 'angular' could not be located

I have encountered an error in my project and despite searching for solutions, I haven't been able to find one that addresses my specific issue. It seems like a simple problem, but I can't figure out what I'm missing. The error arises in th ...

Protractor: the art of inheriting classes

I am working with a complex hierarchy of inheriting classes: The first class inherits ElementArrayFinder, and the second class inherits the first class. Here is my code: 1st class: var util = require('util'); var ElementArrayFinder = require( ...