Ways to incorporate AngularJS variable within a JavaScript function

My current task involves iterating through a JSON file using AngularJS. Below is the function that I am working with:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script>
        function PostsCtrlAjax($scope, $http) {
        $http({method: 'POST', url: 'posts.json'}).success(function(data) {
                $scope.tasks = data;
            });
        }
</script>
<div id="ng-app" ng-app ng-controller="PostsCtrlAjax"> 
        <div ng-repeat="task in tasks.objects">
<script type="text/javascript">     
var adviser1 = new primitives.orgdiagram.ItemConfig("{{task.name}}", "{{task.description}}", "http://www.basicprimitives.com/demo/images/photos/z.png");
</script>
</div>
</div>

When using {{task.name}}, the output shows up as {{task.name}}, rather than the actual content of the variable. How can I make it display the variable's value? Also, when I remove the quotes, nothing is displayed. Any suggestions on how to rectify this?

Would appreciate some guidance on resolving this issue.

Answer №1

Consider revisiting your code structure. Placing a <script> tag inside an ng-repeat may not be the best practice.

You could improve this by creating a simple directive to use within the ng-repeat. Each time the directive is instantiated in the loop, you can execute your function

new primitives.orgdiagram.ItemConfig()
with all necessary parameters.

I've implemented something similar, where instead of calling your function, I am outputting to the console.

Please review the code snippet below or view a working example here

 <!doctype html>
  <html lang="en" ng-app="myApp">
  <head>
   <meta charset="UTF-8">
    <title>Document</title>
     <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
     <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>

      <script>

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

       myApp.controller('PostsCtrlAjax', ['$scope', '$http' ,function ($scope, $http) {

       $scope.tasks = {
        "data" :  [ 
         {
          name: 'Task 01',
          description: 'Task 01 Description',
          url: 'http://www.basicprimitives.com/demo/images/photos/z.png'
         },
        {
          name: 'Task 02',
          description: 'Task 02 Description',
          url: 'http://www.basicprimitives.com/demo/images/photos/z.png'
        }
      ]
    };
  }]);


  myApp.directive('adviser', [ '$compile', function ($compile) {
    return {
     restrict: 'A',
     transclude: true,
     replace: true,
      scope: {
       item : "="
      },
     link: function (scope, element, iAttrs) {

         var template = '<button ng-click="createAdviser(item.name, item.description, item.url)">{{item.name}}</button>';


         scope.createAdviser = function(name, description, url) {

         // var adviser1 =  new primitives.orgdiagram.ItemConfig(name, description, url);

            var adviser =  [name, description, url];

            console.log(adviser)

         }

         element.html(template).show();

         $compile(element.contents())(scope);

       }
     };
   }])

  </script>

  </head>
 <body>


 <div ng-controller="PostsCtrlAjax"> 
   <div ng-repeat="task in tasks.data">
     <div adviser item="task"></div>
  </div>
 </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

Add one string to an existing array

I have a component named ContactUpdater that appears in a dialog window. This component is responsible for displaying the injected object and executing a PUT operation on that injected object. The code for the component is shown below: HTML <form [for ...

Convert to a TypeScript map

Here are the configurations I am working with: type Choice = { value: any, label: any } Additionally, there is a role interface: export interface UserRole { id: number name: string } I have a set of roles: const userRoles:UserRole[]:[ {id:1,name: ...

The JADE form submission is not being captured even though the route is present

I am currently utilizing JADE, node.js, and express to develop a table for selecting specific data. This entire process is taking place on localhost. The /climateParamSelect route functions properly and correctly displays the desired content, including URL ...

Is it possible to set up a local version of the Firebase database for development testing?

Can the actual code on Firebase database be avoided during development by running a local instance and developing using that, similar to other MongoDB and MySQL databases? ...

Unable to display the content

Why isn't the text expanding when I click "see more"? Thanks XHTML: <div id="wrap"> <h1>Show/Hide Content</h1> <p> This code snippet demonstrates how to create a show/hide container with links, div eleme ...

Performing a Node.js PUT call with specified parameters

Attempting to send a PUT request using the 'request' function to the following URL: request({ uri: 'http://apiurl.url/1.0/data?token=' + APItoken, method: 'PUT', data: [{ ...

Arrange items in an array by two criteria

Sorting elements in a JavaScript array can be tricky, especially when trying to order them based on specific criteria like Ptr and Outputs values. In this case, the desired ordering is Node 0 -> Node 2 -> Node 1, where the Output of an element matche ...

Delivering the static index.html file using Django

Currently, I am working on an angular + cordova app within one module. My goal is to utilize the REST api from django for the webserver without incorporating any views (except for serving the angular views). Is it possible to serve the static index.html u ...

Retrieve data from AJAX request using array index

A certain script in my possession is able to extract data from a JSON file and store the name property of each element in an array. HTML <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <script> var names = []; var f ...

Resolve React Issue: Using Functions as React Children is Invalid

As I follow along with a React tutorial, I encountered an error while adding a POST request: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than ...

Struggling to store information in a MongoDB database within my MEAN Stack project

After successfully creating a collection for user LOGIN/LOGOUT and managing to store and retrieve data using Express app and mongoose, I encountered an issue when trying to create another collection. Despite successfully creating the collection, the data w ...

String Replacement in JavaScript

Here's the scenario: I have a string var str="abc test test abc"; Is there a way to specifically replace the second occurrence of "abc" in the string using the str.replace() method? ...

Managing sessions in MEAN stack applications

I am just beginning to learn about Mean and full stack development. I'm struggling with understanding how to handle sessions in a web app - specifically, what aspects should be handled on the server side versus the client side. Can you please explain ...

employing a directive to call upon a controller function triggering a straightforward alert display

I've been learning from this helpful tutorial and I want to make a change in my code so that an alert pops up when the button is clicked. If you'd like to see my code, here's the link to my fiddle I'm wondering how I can connect an el ...

Error: npm encountered a socket timeout issue

Setting up a fresh React application in /home/abhijith/Desktop/React/firstReact/myapp. Installing necessary packages. This process may require a few minutes. Installing react, react-dom, and react-scripts along with cra-template... npm ERR! code ERR_SOCK ...

Minimize an array by organizing objects based on the proximity of their numbers

My array contains the following data: [ { "begin": 870, "end": 889, "spanType": ["plan", "gt-plan"] }, { "begin": 890, "end": 925, "spanType": ["plan", "gt-plan"] }, { "begin": 926, "end": 938, "spanType": ["plan", "gt-plan"] }, { "begin": 939, ...

A guide on displaying names individually in AngularJS

HTML <ul class="ul_nav"> <li ng-repeat="teams in teamArray" style="-webkit-animation-delay: {{$index * 150}}ms"> {{teams.team_name}} </li> </ul> In this section, I am able to sh ...

Filtering an array can be done by selecting a specific item and applying the

An array of objects is present in a JSON file: [ { "department": "Sound Department", "subDepartments": [ "Supervising Sound Editor", "Dialog Editor", "Sound Designer", "Foley Artist", ...

The evaluation of nested directives in AngularJS is not functioning as expected

Recently, I started delving into Angular directives (fairly new to the framework) and encountering a perplexing issue with a nested directive that is being disregarded. My directives are based on the codes of UI Bootstrap's "tabs" and "pane" directive ...

What is the best way to limit the input field to only allow up to 100 characters

I have implemented the min and max attributes in my code <input min="1" max="100" type="number"> Upon hovering over the input field, an error message is displayed stating "please select a value that is no more than 100." I am looking for a way to ...