Using an Angular dynamic ng-model name within an accordion

Looking for a way to make the ng-model name dynamic in this specific situation. Whenever a department is selected, the form needs to be updated accordingly.

Currently, it works with ng-model="department.name", but this is causing some unexpected issues due to internal conflicts. I am exploring the option to set the name as ng-model={{department.name}}, allowing the name itself to be dynamic.

<div ng-app >
  <ul ng-repeat="department in selectedDepartments">
    <li>
      <div>{{department.id}}</div>
      <input type="text" ng-model={{department.name}}" >
    </li>
  </ul>
</div>

function DepartmentController($scope) {

  $scope.selectedDepartments = {};

  $scope.departments = [
  "audit": [{id:0,name:"auditDept0"},{id:0,name:"auditDept1"}],
  "hr": [{id:0,name:"hrDept0"},{id:0,name:"hrDept1"}],
  "finance": [{id:0,name:"financeDept0"},{id:0,name:"financeDept1"}]
  ];

  $scope.selectDepartment = function(name) {
    if(name=="hr") {
      $scope.selectedDepartments =     $scope.departments.hr;
    } else if(name=="finance") {
      $scope.selectedDepartments =     $scope.departments.finance;
    }
  }
}​

I attempted to create a custom directive as follows:

this.app.directive('dynamicModel', ['$compile', '$parse', function ($compile, $parse) {
  return {
    restrict: 'A',
    terminal: true,
    priority: 100000,
    link: function (scope, elem) {
      var name = $parse(elem.attr('dynamic-model'))(scope);
      elem.removeAttr('dynamic-model');
      elem.attr('ng-model', name);
      $compile(elem)(scope);
    }
  };
}]);

However, I am still facing challenges in using

dynamic-model={{department.name}}
.

Thank you!

Answer №1

I believe using dynamic models with JavaScript expressions in ng-models can eliminate the need for a custom directive. You can check out this example for reference.

In your scenario, it seems like you might be interested in something similar to the following:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

    $scope.selectedDepartments = {};

    $scope.departments = {
        "audit": [{id: 0, name: "auditDept0"},
                  {id: 0, name: "auditDept1"}],
        "hr": [{id: 0, name: "hrDept0"}, 
               {id: 0, name: "hrDept1"}],
        "finance": [{ id: 0, name: "financeDept0"},
                    {id: 0, name: "financeDept1"}]
    };

    $scope.selectDepartment = function(name) {
        if (name == "hr") {
            $scope.selectedDepartments = $scope.departments.hr;
        } else if (name == "finance") {
            $scope.selectedDepartments = $scope.departments.finance;
        }
    }

    $scope.selectDepartment('hr');
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
    <ul ng-repeat="department in selectedDepartments">
        <li>
            <div>{{department.id}}</div>
            <input type="text" ng-model="department[name]" ng-value="department[name]"> {{department[name]}}
        </li>
    </ul>
</div>

This suggestion may offer some assistance.

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

Alter the ng-repeat values that are dynamically added from a common source

I am facing an issue where dynamically added ng-repeat values are being changed across all divs instead of the selected one. In my code below, clicking on dynamically appended divs shows a form on the right side allowing input text fields. However, I want ...

Ensure the video frame stretches to fit the full width

I am struggling to make my video frame fill the entire width of the screen. Even though I have tried using CSS, the video container does not stretch to the full width as expected. https://i.sstatic.net/kxyE0.png How can I ensure that the video plays acro ...

showcase every value upon submission in the form with options to edit and delete

Is it possible to display all values submitted in a form with edit and delete buttons? Currently, only one value is being displayed at a time. Whenever a new value is displayed, it replaces the old one. How can this be fixed? You can fin ...

Enhance your Next JS website's SEO with a combination of static pages, SSR pages, and client-side

In my project using Apollo GraphQL with Next JS, I have explored three different approaches to querying and rendering data. The first method involves Static Rendering by utilizing getStaticProps(), which looks like the following: export async function getS ...

I aim to create a solution that leverages the power of JQuery Ajax to fetch data from a web page and then uses that data to populate the $scope object, filling the HTML template

angular.module('spLists', []) .factory('spListsFactory', function ($q) { return { getItems: function (url) { var json, div = $('<div>').css('display', 'non ...

What is the destination for next() in Express js?

I'm new to javascript, nodejs, and express, and facing confusion with the usage of next(). I am trying to make my code progress to the next router using next(), but it seems to be moving to the next then instead. This is what my code looks like: // ...

Issue: The provider "tProvider" is not recognized in the Rails application using angularJS

Having trouble with AngularJS? I encountered an error when minifying my javascript that reads "Error: Unknown provider: tProvider <- t". Interestingly, disabling the minification fixes the issue. I've followed all the tips provided in http://docs.a ...

configure Next.js to exclude a specific subPath within the host from being processed

I've encountered an issue with my public_html directory where there is a folder named blog that is unrelated to my NextJs app. After deploying the app on the host, everything works fine until I try to access the blog section using the following URL: w ...

Block-level declarations are commonly used in TypeScript and Asp.net MVC 5

In my asp.net mvc5 project, I decided to incorporate TypeScript. I created an app.ts file and installed the nuget-package jquery.TypeScript.DefinitelyTyped. Here is a snippet of the app.ts code: /// <reference path="typings/jquery/jquery.d.ts"/> cl ...

Troubleshooting Issues with XMLHTTPRequest Function During Data Insertion

My code is only working when I include this line of code: document.write(str); Essentially, this code opens a new page and writes the inserted data into the database. However, if I attempt to run the code without it, like this: function addcourse2( ...

Disabling a tooltip using the tooltip-is-open attribute is ineffective

I am looking to implement a clickable element with a font awesome icon that can copy data to the clipboard. Additionally, I want to display a tooltip that disappears when the cursor leaves the element. Since I need this functionality in multiple instances ...

Using an if/else statement in a Jade Template to conditionally remove a select option

I'm a beginner with Jade and I've been assigned to add a select option to a webpage. Everything is working well, except for when the drop-down list is empty and the page is refreshed, an empty option element is created. I want to find a way to re ...

Learn the process of adding and concealing items within an Ionic framework

I have a side menu and I need to modify the item displayed based on the user's status. For example, if the user is connected, then the "My Account" item should be visible. But if the user is not connected, then the "My Account" item should be hidden ...

Merge two separate Vue applications into one cohesive application

I have developed two separate Vue apps independently from each other. User Interface Admin Interface Each app has its own routes, store, configs, etc. I came across this helpful comment here which discusses treating each app as a component within a mai ...

Issue identified: Upgrading package (buefy) causes disruptions in project functionality (filegator) - potential import conflicts(?

I am currently working on enhancing features for the self-hosted file storage system called filegator. (The project utilizes single-file components for organization, which is important to note.) (It is built on Vue.js and operates as a Node.js server ...

Using JavaScript Object Constructor to alter text color

Seeking some guidance as a newbie here on how to deal with a problem I'm currently tackling. I understand that using an object constructor may not be the most efficient way to handle this, but I'm eager to enhance my knowledge of objects. My quer ...

Accessing table cell value when clicked using JavaScript or jQuery

I am currently working on an ASP.NET MVC application where I have a table displaying records from the database in razor code. My goal is to extract the record ID "FeeZoneID" from a cell value when the delete link in the last column is clicked, and then t ...

Sort the elements within the *ngFor loop according to the category upon clicking the button in Angular

Currently, I have a collection of items that I am iterating through using *ngFor. Above this list, there are category buttons available as shown in the HTML snippet below. My goal is to enable filtering of the list based on the category of the button click ...

The curly braces in AngularJS are failing to display the values on the HTML page

After trying various articles and solutions to different questions, I am still unable to resolve my issue. I am working on a blank ionic project and it is running smoothly in my browser using ionic serve without any errors. However, instead of displaying ...

Issue with Mobile Touch Screen Preventing Vertical Scrolling

Currently experiencing difficulties with a div element that is not allowing touch and vertical scroll on mobile devices. Although scrolling works fine with the mouse wheel or arrow keys, it does not respond to touch. Have tested this on various devices and ...