Retrieve the child scope of ng-repeat beyond the ng-repeat iteration and establish a two-way data binding

With my ng-repeat, I am attempting to include ng-model inside each repeated li, followed by two-way data binding outside of the ng-repeat. You can see the example in this jsbin: http://jsbin.com/yutinifivi/edit?html,js,output

I have searched extensively for a solution regarding ng-model and ng-repeat, but have not been able to find what I need.

If anyone is willing to take the time to understand my issue, I would greatly appreciate the help in furthering my understanding of AngularJS.

Here is the relevant code:

(function(){
  var app = angular.module("myApp",[]);
}());

(function(){
  var myCtrl = function($scope){
    $scope.selection_add = {};
    $scope.selection_edit = {};
    $scope.selection_delete ={};
    $scope.categories = [ 
        {"name": "Sport", "id": "50d5ad" } , 
        {"name": "General", "id": "687ffr" },
        {"name": "Activities", "id": "678ffb" },
        {"name": "Regards", "id": "678fff" },
        {"name": "Thanks", "id": "678fer" },
        {"name": "Goes", "id": "678fgf" },
        {"name": "Oppertnities", "id": "674ffr" },
        {"name": "Convince", "id": "654ffr" },
        {"name": "Mopols", "id": "623ffr" } 
    ];
    
    $scope.setCurrentCategory = function setCurrentCategory(category) {
      $scope.currentCategory = category;
    };
  };
  angular.module("myApp")
  .controller("myCtrl", myCtrl);
}());
<!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>
  <title>JS Bin</title>
</head>
<body>
<div class="container" ng-controller="myCtrl">
  <div>
          <table>
              <tr>
                  <th>add</th>
                  <th>edit</th>
                  <th>delete</th>
              </tr>
              <tr ng-repeat="category in categories" ng-click="setCurrentCategory(category)">
                  <td><input id="{{category.id + '_add'}}" ng-model="selection_add[category.id]" type="text>{{category.name}}</td>
                  <td><input id="{{category.id + '_edit'}}" ng-model="selection_edit[category.id]" type="text>{{category.name}}</td>
                  <td><input id="{{category.id + '_delete'}}" ng-model="selection_delete[category.id]" type="text>{{category.name}}</td>
              </tr>
          </table>
    
        <h1>Add for {{currentCategory.name}}</h1>
        <input type="text" ng-model="selection_add[currentCategory.id]>
        <h1>Edit for {{currentCategory.name}}</h1>
        {{selection_edit[currentCategory.id]}}
        <h1>Delete for {{currentCategory.name}}</h1>
        {{selection_delete[currentCategory.id]}}
      </div>
</div>
</body>
</html>

Answer №1

When working with objects and input fields, it's important to use a specific property as the model for each input. Make sure that when displaying data, you are pointing to the correct property that you want to change, rather than just using the entire object.

To address this issue, I've implemented a click function that saves the current category and then displays data accordingly. You can see a demo of this solution here.

Here are the changes made to the html:

<tr ng-repeat="category in categories" ng-click="setCurrentCategory(category)"> <-- ensure to include ng-click to store currentCategory -->

    <!-- currentCategory is used to update the model and display the category name -->
    <h1>Add for {{currentCategory.name}}</h1>
    <input type="text" ng-model="selection_add[currentCategory.id]">
    <h1>Edit for {{currentCategory.name}}</h1>
    {{selection_edit[currentCategory.id]}}
    <h1>Delete for {{currentCategory.name}}</h1>
    {{selection_delete[currentCategory.id]}}

Include this in the controller:

$scope.setCurrentCategory = function setCurrentCategory(category) {
  $scope.currentCategory = category;
};

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

Encountering difficulties accessing the array in the controller through ajax

Having trouble receiving an array of data from AJAX to the controller. $.ajax({ type: "POST", url: "/Home/List", traditional: true, contentType: 'application/json', data: { "Query&quo ...

Customizing the color scheme of specific components using Material UI inline styling

I am currently customizing my TextFields from Material-UI. My background is black and I want both the textField border and text to be white. Here's the relevant part of my code: render() { const styles = { width: { width: '90%& ...

Unlocking the secret to obtaining durable identity provider tokens for JavaScript in web browsers

Currently, I am working on implementing browser-side JavaScript code for login with Facebook, Amazon, Twitter, and Google using Cognito. I have reached a point where I am able to obtain client tokens for all four platforms. However, the issue is that thes ...

What could be causing my Chrome extension to function on Mac but not on a PC?

I created a basic Chrome extension that includes a background page with the following code: <script type="text/javascript> chrome.tabs.onDetached.addListener(function(tabId, info){ var id = tabId; chrome.tabs.get(id, function(tab) { ...

angular fullstack is failing to execute

Hello, I followed the complete installation process of npm, node, and angular fullstack on CentOS 6 32-bit with all necessary dependencies such as Ruby updated. After that, I proceeded to install angular fullstack using the following command: # npm insta ...

What is the general consensus on combining SWR with Redux - is it considered a best practice?

I am currently incorporating both SWR and Redux into my code. Here is how I'm using them together: const vehiclesStates = useSelector(({ vehiclesStates: state }) => state); // REDUX const response = useFetch("/vehicles/states") // SWR con ...

The methods $.get() and $.ajax() in jQuery are failing to retrieve data from PHP

I've been trying to use a script to display a message from a PHP file after a click event, but I've run into issues with both jQuery $.get() and $.ajax(). With $.ajax(), I get an alert with an empty message, while $.get() alerts "null". load.php ...

Ensuring a radio button is pre-selected by default in React by passing in a prop

Assume I have a React function similar to this function Stars({handleStarClick, starClicked}) { if (starClicked === 3) { document.getElementById('star3').checked = true } return ( <div className="rate"> ...

Using AngularJS to interact with resources by passing in the scope parameter

My issue is as follows: I am attempting to call a resource with a specific parameter, but I keep encountering the following error: [$resource:badcfg] I have spent the last 3 hours trying to resolve this, but to no avail. When I call the resource like th ...

What is the best way to use async await to listen for an event in a child component with Vue-router?

To prevent users from unintentionally leaving an unsaved form, I am looking to implement a custom modal alert system with vue-router. Although the use of the standard browser alert box is an option, beforeRouteLeave (to, from, next) { const answer = wi ...

The scrolltop animation does not appear to be functioning properly on iOS devices

I have implemented a JavaScript effect to increase the line-height of each list item on my website as you scroll. It works perfectly on my Macbook and Android Smartphone, but for some reason, it's not working on an iPhone. Can anyone provide a solutio ...

Omit child DIV element in JavaScript and the Document Object Model

I have a situation with two div elements. One is <div class="card" id="openWebsite"> and the other is a sub-division <div class="card__btn"> Here's the issue: When someone clicks on the main div, they get red ...

The functionality of Vue slot-scope seems to be restricted when used within nested child components

Here is the component configuration being discussed: Vue.component('myComponent', { data () { return { msg: 'Hello', } }, template: ` <div class="my-component"> <slot :ms ...

Guide to showing several charts simultaneously within a single controller utilizing Chart.js with Angular JS

I am looking to incorporate two distinct charts with different sets of data using chart.js within the same controller. However, I am currently facing difficulties as I am unsure of the proper procedure. Could someone kindly provide guidance on how to achie ...

`Finding specific components or pages within an AngularJS application`

I came across a unique webpage for an Angularjs based project. I am looking to develop an autofiller and autoclicker feature. To achieve this, I need to identify pages or subpages uniquely (especially in cases of Ajax-based changes). The major challenge ...

Exploring the internet with selenium

I'm currently facing difficulties navigating a website for information scraping with Selenium. The issue lies in the site's use of ng-click to update a table, requiring me to activate different tabs on the page in order to access the desired data ...

Adding a class to the following DIV and smoothly transitioning the current one out can be achieved using a dynamic number of items in multiple instances

Is there a way to create a scalable CSS slideshow for text divs without using images? Here is the current HTML structure: <div class="mb-panel-container cf"> <div class="mb-panel-section mb-slider"> <div class="mb-panel active" ...

React- The Autocomplete/Textfield component is not displaying properly because it has exceeded the maximum update depth limit

My autocomplete field is not displaying on the page even though I wrapped it with react-hook-form for form control. When I check the console, I see this error: index.js:1 Warning: Maximum update depth exceeded. This can happen when a component calls setSt ...

Refresh data with Axios using the PUT method

I have a query regarding the use of the HTTP PUT method with Axios. I am developing a task scheduling application using React, Express, and MySQL. My goal is to implement the functionality to update task data. Currently, my project displays a modal window ...

SignalR does not actively send messages to clients

Currently, I'm working on implementing a feature that notifies users when long-running jobs are completed using SignalR in an AngularJS application. To achieve this, I have grouped users based on their names, creating a unique group for each user cont ...