Encountering an issue with Angular directive attributes

I am attempting to create an angular directive that will extract a substring from a passed-in attribute. Below is the code I have written:

HTML:

<body ng-controller="MainCtrl">
     <div><substring message="This is a test."></substring></div>
     <div><substring message="So is this." ></substring></div>
</body>

Angular/Javascript:

var app = angular.module('myapp', []);

app.controller('MainCtrl', function($scope) {

});

app.directive('substring', function () {
return {
    restrict: 'AE',
    replace: true,
    scope: { text: '=message' }, 
    link: function (scope, elem, attrs) {
        //alert(attrs.message); 
        var str = attrs.message;

        scope.text = str.substring(1, 4);
    },
    template: '<H1>{{text}}</H1>'
};
});

Upon testing this code, I encountered the following error:

HTML1300: Navigation occurred. File: directive.html Error: [$parse:syntax] Syntax Error: Token 'is' is an unexpected token at column 6 of the expression [This is a test.] starting at [is a test.].

I've also attempted changing

'=message' to '@message'

However, this resulted in the substring functionality within the link function being ignored.

Why is this error occurring? Is Angular failing to recognize the content within the quotation marks as a string and instead trying to interpret it as a command? Most importantly, how can I resolve this issue?

Thank you.

Answer №1

Using @ for text binding is the key to making your code run smoothly.

Here's a practical example:

var app = angular.module('myapp', []);

app.controller('MainCtrl', function($scope) {

});

app.directive('substring', function() {
  return {
    restrict: 'AE',
    replace: true,
    scope: {
      message: '@'
    },
    link: function(scope, elem, attrs) {
      //alert(attrs.message); 
      var str = attrs.message;
      scope.text = str.substring(1, 4);
    },
    template: '<H1>{{text}}</H1>'
  };
});
<!DOCTYPE html>
<html ng-app="myapp">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body ng-controller="MainCtrl">
  <div>
    <substring message="This is a test."></substring>
  </div>
  <div>
    <substring message="So is this."></substring>
  </div>
</body>

</html>

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

Tips for shrinking the circumference of a circle

Currently, I have a circular div that has been styled using CSS animations. My goal is to keep the size of the circle consistent when it moves to the bottom, but reduce its size when it bounces back to the top. I am uncertain if this can be achieved solely ...

What sets apart these two JavaScript namespaces?

My main goal is to expertly organize my javascript code by eliminating any global elements. I came across two namespace declaration methods in this informative post, and now I'm looking for your input on the advantages and disadvantages of each. ...

What is the best way to present retrieved JSON data from a database in Node.js without using the JSON format?

Here is the code snippet: var http=require("http"); var fs = require("fs"); var express = require("express"); var app = express(); var path = require("path"); var mysql = require('mysql'); var ejs = require("ejs") var bodyParser = require(&apos ...

The performance of Three.js is directly influenced by the quantity of objects present

Just completed a project in WebGL using Javascript and the 3D library known as three.js Unfortunately, the performance of the project is less than impressive - slow from the start with occasional moments of adequacy. In this game, there are: 1 car, 6 ora ...

Identifying Mistakes to Address Promise Failures

I encountered unhandled promise rejection errors and attempted to catch them and log them after each .then statement. Unfortunately, I ran into an 'unexpected token' issue when running the code on my server due to the period before .try. Despit ...

"Can someone guide me on where to place the JavaScript code within this Bootstrap snippet when working with CakePHP

I'm currently delving into CakePHP and am eager to incorporate this Bootstrap code snippet from onto my website. I've successfully added the HTML to the .ctp file in the Pages directory and styled it with custom.less, but I hit a roadblock when ...

Enhancing the background of a website with the power of CSS

I am looking to create a customized table without the balls/pots in it. The number of rows on the y-axis will vary depending on the number of names I have, and can be more or less. The values on the x-axis are determined by a parameter included in the URL ...

Passing data between parent and child components within an Angular application using mat tab navigation

I am currently working on a project, which can be found at this link. Current Progress: I have implemented a mat tab group with tabs inside the app-component. When a tab is clicked, a specific component is loaded. Initially, most of the data is loaded in ...

Learn how to dynamically import and load components in VueJS while rendering a list

I am currently rendering a list. <div v-for="msg in messages"> <div v-if="msg.type==='component'"> <component v-bind:is="getComponent(msg.component)" :data="msg.data" :text="msg.text"></component> </div> ...

Disabling a specific dropdown within ng-repeat in AngularJS

I've encountered a problem with the ng-repeat in my HTML code: <div ng-repeat="a in items"> <div> <span>{{a.name}}</span> </div> <div> <select ng-model="a.c_id" ng-options="d.c_id as d.description ...

The tools needed for securing a web application with ExpressJS include the use of

I recently implemented an upload function using connect-form with formidable and https://github.com/ctavan/express-validator. While attempting to sanitize an image from XSS, I encountered a 'TypeError: Cannot call method 'replace' of undefin ...

What steps should I take to ensure that jQuery functions remain functional on loaded code?

I have implemented modals on all my pages except for the first one to save time. Here is the script that loads my modals: $(function () { $('#header').load('reusenavbar.php'); $('#loginModal').load('reuseloginmo ...

Using an array as a data structure for a d3.js tree layout

I'm looking to use d3.js to create a diagram using the tree layout. Instead of the typical flare json structure with hierarchical children, I have an array representing different timesteps that I want to transform into a tree. My plan is to adjust the ...

Using JQuery to visually enhance the menu selection by displaying an image and altering the background color upon hovering

Hello fellow JQuery/Javascript beginners! I recently put together a menu and wanted to add some interactive elements. Specifically, I want the background color to change when a user hovers over an item (simple enough with CSS), but I also want to include a ...

AngularJS routing that is tailored to form input

I am trying to create a dynamic html page where the user can input form variables. My goal is to use AngularJS routing to navigate to different URLs based on the form inputs. Does anyone have advice or guidance on how I can achieve this functionality? ...

When using keyBy in Laravel, the response may return an object instead of an array

Currently, I am in the process of developing a project where I am setting up a back-end RESTful API using Laravel and a front-end with angularJS. Initially, from my controller@index, I was returning a simple all()->toArray() like this: A. return Respo ...

TABULAOTR, The complete table calculation is failing to be retrieved

Apologies for any language mistakes, as I am Russian :)I am using Tabulator but facing an issue where the table footer is not being printed. I am also unable to retrieve data from the footer. The footer simply doesn't show up and I'm unsure of wh ...

Changing the rotation of an object in THREE.js to match Canvas rotation

Hello amazing minds of stackoverflow. I am in the process of converting three js mesh positions to html5 canvas positions. While I have successfully converted vector3 position to canvas position, I am facing difficulties with converting mesh rotation to ca ...

I need assistance with an issue on my Google Dev Console, as it keeps showing an error stating that ".getcontext is

Looking for some assistance here as my development console keeps displaying an error: Uncaught TypeError: canvas.getContext is not a function. Here is the problematic code snippet: `var canvas = document.createElement; var c = canvas.getContext("2d&qu ...

What is preferable: defining JSON schema properties or utilizing oneOf conditions within an array of objects

I am looking to represent a variety of objects in a schema through an array called contents. This array can include any number of elements, but they must fall into one of two categories: one type represents text while the other type represents images. Up ...