Angular directive mapping an object that contains a function within it

I am attempting to create a directive with an object argument that includes a property called map which can be a function.

However, each time I run it, I encounter the following error:

https://docs.angularjs.org/error/$parse/syntax?p0=%7B&p1=is%20unexpected,%20expecting%20%5B%7D%5D&p2=159&p3=%5B%7B%20name%20:%20%27Nom%27,%20map%20:%20%27id%27%20%7D,%7B%20name%20:%20%27Description%27,%20map%20:%20%27titre_fr%27%20%7D,%7B%20name%20:%20%27Type%20de%20Valeur%27,%20map%20:%20%27type_valeur%27%20%7D,%20%7B%20name%20:%20%27test%27,%20map%20:%20function(d)%20%7B%20return%20%27ok%27;%20%7D%7D%5D&p4=%7B%20return%20%27ok%27;%20%7D%7D%5D

This is how my directive is defined :

directive.js

.directive('apiTable', ['$rootScope', 'APIService', function($rootScope, APIService)
{
    return {
        restrict : 'E',
        templateUrl : '/js/angular/app/ui/api-table.html',
        transclude : true,
        scope :
        {
            mapping : '=',
            route : '@'
        },
        controller : function($scope)
        {
            $scope.data = [];
            $scope.page = 0;
            this.mapResult = function(data)
            {
                for(var i = 0; i < data.length; i++)
                {
                    var temp = [];
                    for(var j = 0; j < $scope.mapping.length; j++)
                    {
                        temp[0] = i + 1;
                        if(typeof(data[i][$scope.mapping[j].map]) !== 'undefined')
                        {
                            if(typeof(data[i][$scope.mapping[j].map]) == 'function')
                            {
                                console.log('ok')
                            }
                            else
                            {
                                temp[j + 1] = data[i][$scope.mapping[j].map];
                            }
                        }
                        else
                        {
                            temp[j + 1] = "";
                        }
                    }
                    $scope.data.push(temp);
                }
            };
            this.getData = function(p)
            {
                APIService.getData($scope.route, p)
                    .then(function(data)
                    {
                        this.mapResult(data.results);
                    }.bind(this));
            };
            this.getData({ p : $scope.page });
        }
    };
}])

And here is how it is called :

view.html

<api-table route="_dictionnaryAPIFindByDomain" mapping="[{ name : 'Nom', map : 'id' },{ name : 'Description', map : 'titre_fr' },{ name : 'Type de Valeur', map : 'type_valeur' }, { name : 'test', map : function(d) { return 'ok'; }}]"></api-table>

Answer №1

It is not allowed to declare functions within an Angular expression, including inside the ng-init directive.
Learn more about Angular Expressions

Interestingly, this restriction also extends to object properties.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  {{ {a:'b',c:function(){}} }}
</div>

The simplest solution is to encode the object to JSON and then parse it.

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

Having trouble establishing a connection between Node.js server and Google Directions API

Recently, I've been facing an issue while trying to establish a connection with the Google Directions API through my node server using a callback function. Surprisingly, it was working fine just a few days back, and now it seems like I accidentally br ...

Error: Callstack Overflow encountered in TypeScript application

Here is the code snippet that triggers a Callstack Size Exceeded Error: declare var createjs:any; import {Animation} from '../animation'; import {Events} from 'ionic-angular'; import { Inject } from '@angular/core'; exp ...

Having trouble loading script files with JSDOM in NodeJS?

I'm currently experimenting with loading an HTML page in jsdom to generate graphs, but I'm facing challenges in getting the JavaScript to execute. Here's the HTML page I'm trying to load, which simply renders a basic graph: <html&g ...

Ways of converting a negative lookbehind into an ES5-friendly expression

In my code, I have a RegExp that works perfectly, but it only functions with ES2018 due to its use of negative lookbehinds. The problem is that a library is using this RegExp function, so modifying how it's used is not an option. I attempted to add n ...

Choose an option from the drop-down menu and transfer the selected value to the following page using a hidden

Struggling to capture the selected value from a combo box and set it to a hidden field in order to retrieve it on the next page. Need some assistance with this task. Here is my form tag: <form class="well" name="ddm" id="ddm" style="margin-left: 30px; ...

The challenge of PHP's HTTP_REFERER

I am experiencing an issue with http_referer. In my setup, I have two files: index.php and index.html. The index.php file contains a form that, upon submission, includes information like the http_referer. On the other hand, the index.html file runs an aja ...

The configuration object is invalid. Angular has initialized Webpack using a configuration object that does not align with the API schema

When attempting to run the angular application with "ng serve -o", I encountered an error message stating "Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema." Prior to this issue, "n ...

retrieve object from s3 using angular and open it as a pdf

I'm attempting to access a file from an s3 bucket using Angular and display it as a PDF. I have a node service set up to retrieve the object, which I then call from Angular. However, when I try to open the PDF in Angular, it appears as a blank (white) ...

Align the inline text at the center as if it were an inline-block element

Currently working on a design that appears deceptively simple, yet I'm encountering challenges in centering it while keeping the text aligned to the left. https://i.sstatic.net/qhf6p.png In an attempt to have the background span only the actual text ...

Discord.js: AbortError: The request was cancelled by the user

Recently, while working on my ticket system and the process for logging transcripts, I encountered an unexpected error that caused transcripts to fail sending. This issue never occurred before. The error message displayed was: [Error Handling System] Multi ...

Chrome is missing the cookie value

There seems to be a strange issue occurring with the cookies in one of my programs. I have set a cookie named allowed_apps which contains the list of allowed apps for the user. Interestingly, when a user logs in using Google Chrome, the allowed apps are di ...

Setting default parameters for TypeScript generics

Let's say I define a function like this: const myFunc = <T, > (data: T) => { return data?.map((d) => ({name: d.name}) } The TypeScript compiler throws an error saying: Property 'name' does not exist on type 'T', whic ...

Unable to run EJS script inside ajax 'success' function

I am facing an issue with my EJS page that utilizes AJAX to retrieve data. After loading the data, I intend to add specific content to a div. Within the added content, there are checkboxes controlled by the following script: <script> $('#select ...

Asynchronous requests in Node.js within an Array.forEach loop not finishing execution prior to writing a JSON file

I have developed a web scraping Node.js application that extracts job description text from multiple URLs. Currently, I am working with an array of job objects called jobObj. The code iterates through each URL, sends a request for HTML content, uses the Ch ...

Using Multer and Passport, we can upload and store a file in MongoDB by utilizing Node.js and Express

Despite searching through various similar questions, I have yet to find a solution to my current dilemma. The issue at hand involves intercepting a signup post request using passport, but also needing to upload and save the profile photo to the database. ...

Cordova encountered an error: Execution of inline script was denied due to violation of Content Security Policy directive

As I delve into the world of Cordova and jquery mobile, I encountered a perplexing error that reads: Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self' data: gap: 'un ...

What is the best way to display my images within Material UI Cards using React with Typescript?

I'm currently faced with a challenge of rendering images within Material UI's cards. I am successfully passing props to each card from a constants.tsx file where the heading, description, and bodyHeader are all properly read, but for some reason, ...

Issue Encountered with FabricJS: Unable to Execute 'drawImage' with Image Subclass

I'm working on a project that requires me to add images of different types to a canvas, save them as JSON, and then load them again. The unique property needed for each type is simply the differentiation in type. To achieve this, I have created a new ...

problem with saving session data

I am attempting to access data from another page using session storage. On my initial page, named home.html function go_to_faq(qnum){ window.open('FAQ.html', '_blank'); sessionStorage.setItem('key2', qnum); } <a s ...

Transitioning from using $http to Restangular has caused issues with our tests now not passing

I am currently working with the following controller: 'use strict'; angular.module('App') .controller('LoginCtrl', function ($scope, $state, Login, localStorageService, Message, authService) { $scope.submit = function ...