Sending information from controller to directive in angularjs

I'm currently facing an issue where I am attempting to send data from a controller to a directive in order to dynamically update rows in a table. However, despite my efforts, the table does not reflect any updates and there are no error messages displayed in the console.

Below is the HTML code snippet:

$<div ng-app="roleManagement" ng-controller="RoleManagementCtrl">
<h1> Role Management</h1><hr/>
<div class="container-fluid">
    <form >
        <div class="form-group row">
        <button type="button" class="btn btn-primary col-md-1" 
         ng-click="query(roleId, userId)">Query</button>
         <button type="button" class="btn btn-primary col-md-2 col-md-offset-               
         1">Edit Role</button>
</div>

<div class="form-group row">
    <label class="col-md-1" >Role ID</label>
    <select class="col-md-2 col-md-offset-1" ng-model="roleId">
    <option></option>
    <option ng-repeat="roleID in roleIDS | unique :roleID">{{roleID}}</option>
    </select>
</div>

<div class="form-group row">
    <label class="col-md-1">User ID</label>
    <select class="col-md-2 col-md-offset-1" ng-model="userId">
        <option></option>
        <option ng-repeat="userID in userIDS | unique :userID">{{userID}}          
        </option>
    </select>
</div>
</form>
</div>
<hr/>


<div ng-controller="RoleManagementCtrl">
    <my-table users = 'users'></my-table>
</div>
</div>

The following depicts my controller and directive setup. My intention is to pass on $scope.users via the controller to the directive:

$'use strict';
angular.module('roleManagement', ['angularUtils.directives.dirPagination'])
    .controller('RoleManagementCtrl', ['$scope', '$http', 'localStorageService',    
    function($scope, $http, localStorageService) {
    var init = function () {
        $http({
        method: 'GET',
        url: 'http://172.16.0.26:7001/Taisys_Server_Current/getAllRoles',
        headers: {'X-Auth-Token': localStorageService.get('jwtTokens')}
        }).success(function (response) {
        $scope.roleIDS = response;
        });
        $http({
        method: 'GET',
        url: 'http://172.16.0.26:7001/Taisys_Server_Current/getAllUsers',
        headers: {'X-Auth-Token': localStorageService.get('jwtTokens')}
        }).success(function (response) {
        $scope.userIDS = response;
        });
        };
        init();
        $scope.query = function (roleId, userId) {
        ...
      );
      element.replaceWith(html);
    }
  }
});

Answer №1

.directive('myTable', function () {
  return {
      restrict: 'E',
      scope:{data:'=data'}
      link: function (scope, element, attrs) {
      var html = '<table>';
      html += '<th>Product Name</th>';
      html += '<th>Product ID</th>';
      html += '<th>Category Name</th>';
      html += '<th>Category ID</th>';
      angular.forEach(data, function (product, index) {
          if ('products' in product) {
              angular.forEach(product.products, function (prod, index) {
              html +='<tr>';
              html += '<td>' + product.productName + '</td>';
              html += '<td>' + product.productID + '</td>';
              html += '<td>' + prod.categoryName + '</td>';
              html += '<td>' + prod.categoryID + '</td>';
              html +='</tr>'
              })
            }
          }
      );
      html += '</table>';
      element.replaceWith(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

Difficulty arises when attempting to run code when a checkbox is not selected

In my form validation process, I am facing an issue where I need to validate certain values only if a checkbox is unchecked. If the checkbox is checked, I want to use the values that were previously added. However, none of the existing code snippets seem t ...

Connecting an HTML box to a JavaScript function for the desired outcome: How to do it?

My goal is to connect the input box with id="b" (located inside the div with id="but1") with a JavaScript function that calculates values within an array. Although my junior logic review didn't detect any issues in the code, what mistakes could I have ...

Issue with my "message.reply" function malfunctioning in Discord.JS

I'm currently learning how to use discord.Js and I am facing an issue with my message.reply function not working as expected. I have set up an event for the bot to listen to messages, and when a message containing "hello" is sent, it should reply with ...

Tips on integrating TypeScript into JavaScript

Currently, I am working with a node.js server.js file. var http = require('http'); var port = process.env.port || 1337; http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res ...

configure Jquery AJAX settings using a JavaScript object

While working with a jQuery AJAX call, I encountered an issue where defining the ajax properties 'from scratch' worked perfectly fine. However, when setting the same values in a JavaScript object and then using that object to define the ajax requ ...

Steps for retrieving user timezone offset and transmitting it to the server in an ASP.net application

I need assistance with capturing and sending a user's timezone or offset when they successfully sign in. I came across the "getTimezoneOffset" method in JavaScript, but I'm unsure how to automatically send this data without the user explicitly in ...

Why does Asp.net Webform load twice every time I click on the form link?

In my asp.net webform project, I am encountering an issue where the page is running twice when clicked. The problem arises when calling two functions (Fill DropDowns) on the Page_Load Event. During debugging, it was observed that the control enters the Pa ...

Is there a way to insert a value into the input field using JQuery or JavaScript?

After reading my previous post on posting values into an input box, a commenter suggested using JQuery or Javascript. For more code and information, please refer to the link provided above. <label>Date</label>:&nbsp&nbsp <input sty ...

Transform Vue military time to regular time format

I am retrieving the arrivalTime from todos.items. As I fetch the arrivalTime, it is sorted using the sortedArray function(), which converts the times to military time. Is there a way to change the sorted military time values to standard time format after s ...

JavaScript Tutorial: Updating the maximum value of a gauge chart

Is there a way to dynamically change both the total and max values in my current code? The maximum value needs to be dynamic based on the filter applied. Here is the code snippet: resource1=[ "//cdn.jsdelivr.net/raphael/2.1.0/raphael-min.js", "//cd ...

Working with HTML5 canvas to draw multiple images

Here is the code I'm working with: http://jsfiddle.net/zyR9K/4/ var Enemies = { x: 25, y: 25, width: 20, height: 30, speed: 0.5, color: "#000", draw: function () { canvas.fillStyle = ...

Display a Button in AngularJS When the Model is Modified

Within an ng-repeat, I have a model: <tr ng-repeat="expert in experts"> <td>{{expert.expertName}}</td> <td ng-mouseleave="editMode = false"> <span ng-hide="editMode" ng-click=" ...

Create a pop-up window within a single controller using Angular.js

I followed a tutorial to create this code. I am interested in learning how to utilize just one controller for generating the dialog box. Currently, I am using two controllers for this project. Any guidance or tips would be greatly appreciated. View my cod ...

Split the string into individual parts and enclose each part in HTML using JavaScript

Currently, I am utilizing a content editable div to create tags. Upon pressing the return key, my objective is to select the preceding text (excluding the prior tags) and transform it into a new tag. The format for a tag will be enclosed within . For insta ...

What is the best way to combine two arrays of objects in AngularJS?

How can I merge the existing object array with another one in AngularJS to implement the "load more" feature? Specifically, I want to add the AJAX response to the existing data each time. Currently, I have a variable called $scope.actions that holds the ...

Establishing the Header for CORS AJAX Request

I am attempting to initiate an AJAX call from one server to a JSON endpoint on another server. I have come across suggestions regarding setting the CORS header, but I am unsure about the specific steps required. The issue arises when making a request from ...

Encountering an error in AngularJS: Issue with require(...) function, along with a runtime error in Node

I have been working on a code similar to the one available here However, when I try to run node web.js, I encounter a TypeError: require(...) is not a function What could be causing this error? Where might the issue lie? Below is my current web.js set ...

Tips for coordinating an Ajax onClick action with an onUpdate event

I am working on a table that will display the rights of a selected user. The columns represent roles and the rows represent functions. Each cell in the table contains a Wicket AjaxCheckBox, which triggers an action using the onUpdate event. Additionally, I ...

Automate the process of adding or removing a class created by material ui through programming

Is there a way to dynamically manage the material-UI classes I declared in makeStyles()? Below is the code snippet: import React from 'react'; import { DropboxIcon, GoogleDriveIcon, BoxIcon } from '../components/icons'; import { makeSt ...

A guide on determining the return type of an overloaded function in TypeScript

Scenario Here is a ts file where I am attempting to include the type annotation GetTokenResponse to the function getToken. import { ConfigService } from '@nestjs/config'; import { google, GoogleApis } from 'googleapis'; import { AppCon ...