Observing ng-model within various nested ng-repeat loops

Here is a snippet of code that I am struggling with:


    <div ng-repeat="category in categories">
        <div ng-repeat="(key, value) in category">
            {{ key + ":"}}
            <select id={{key}} class="my_select"
                    data-ng-model="key.type"
                    data-ui-select2="{}" multiple>
                <option ng-repeat="c in value"
                        ng-selected="(filters[key].length>0) && (filters[key].indexOf(c.trim()) !== -1)" >
                    {{c.trim()}}</option>
            </select>

        </div>
    </div>

In my controller, I have the following code which does not seem to work (console log does not display anything when selection changes):

$scope.$watch('key.type', function(newValue, oldValue){
console.log("" +newValue + " " + oldValue);
}, true);

I'm looking for a way to watch these selects in this specific situation. I have tried various solutions related to Angular, ng_repeat, and ng_model but none of them have resolved my issue. Any assistance would be greatly appreciated.

This is what I aim to achieve: I have categories like [{category : [ laptop, TV]}, {cpu : [ Core i5, Core i7]}] and I want to create two select elements to retrieve selected data using select2 with multiple items.

Answer №1

Utilizing the ng-repeat directive creates a specific scope that is only accessible within the designated block for ng-repeat. This block inherits all properties from its parent block.

Essentially, this setup enables access to the key property within the ng-repeat block but restricts access outside of it, preventing functionality like placing a $watch.

To address this issue, you should utilize the ng-change directive, specifically designed to respond to changes in the select tag.

To implement this directive, add it to the select tag as shown below:

<div ng-repeat="category in categories">
    <div ng-repeat="(key, value) in category">
        {{ key + ":"}}
        <select id={{key}} class="my_select"
            data-ng-model="key.type"
            data-ui-select2="{}"
            data-ng-change="changeInSelect(key, value)" multiple>
            <option ng-repeat="c in value"
                ng-selected="(filters[key].length>0) && 
                (filters[key].indexOf(c.trim()) !== -1)" >
                    {{c.trim()}}
            </option>
        </select>
    </div>
</div>

Next, define a function in your controller to handle this directive:

$scope.changeInSelect = function (key, value) {
    // Add your custom logic here
};

Answer №2

One solution I discovered was to make modifications to the select2.js file that incorporates select2 into Angular.

    $timeout(function () {
      elm.select2(opts);

      // Set initial value - Unsure if necessary, but seems to be required
      elm.select2('data', controller.$modelValue);
      elm.on('change', function(a){
          scope.$emit('select2:change', a);
      });

You can then utilize the following code in your controller to monitor changes:

    $scope.$on('select2:change', function (event, element) {

    if(element.added){
        console.log(element);
        console.log(event);
        $scope.updateCategories(event.targetScope.key, element.added.text.trim());
    }
    if(element.removed){
        console.log("Removed");
        $scope.cleanUpOldStuff(event.targetScope.key, element.removed.text.trim());
    }
});

While not perfect, it gets the job done...

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

The directive fails to refresh when there are modifications made to the service model

My application's model is stored in a service: angular.module('adminClient').factory('myApi', function () { var model = {}; model.myObject = { label: 'New York City' }; return { model: fu ...

Is there a way to hide the thumbnail image when the title is hovered over without using CSS?

I'm currently using a simple jQuery script to switch between two thumbnails when hovering over a div. The code works perfectly for the .thumbs class, but I also want this functionality to work with the post titles. Unfortunately, adding the .headline ...

Achieving full content height with sticky footer

Revise I have made updates to a JSFiddle demo for users to test out. @Aspiring Aqib has offered a working solution using javascript, but CSS solutions are still encouraged. Original Request I successfully implemented a sticky footer following the guidel ...

Combining broken down values within a loop

https://i.sstatic.net/PI3NI.png Take a look at this image, then review the code I've provided: function addNumbers() { var inputList = document.getElementById("listInput").value.split(" "); for(i = 0; i <= inputList.length; i+=1) { ...

Customize the number of slides in Glide.js after navigating using the controls

I have incorporated a glide JS carousel to display content in a carousel format. The documentation for this repository can be found on their official website as well as on Github. Here is my current code snippet: jQuery( window ).load(function() { va ...

Interacting with a 3D model using the mouse cursor in a three

After stumbling upon the three.js library recently, I've been spending several days experimenting with it. I am eager to incorporate a mouse event into my project similar to this example where the head of the skull follows the cursor. However, I want ...

Error encountered with Angular-UI-Calendar: Attempting to access the 'length' property of an undefined value not allowed

I keep encountering this error repeatedly, even though the app functions properly once it is fully initialized. Here's the rundown of my environment: - liveaddress.js - jquery 1.10.2 - jqueryui 1.10.4 - angular 1.2.15 (base, -route, -cookies, -resourc ...

Exploring the intricacies of password reset functionality in Node.js and Angular

I am currently exploring the implementation of password reset and forgot password features using AngularJS (1.x) with Nodejs as the backend. After coming across this informative article on Nodejs backend setup, I stumbled upon a relevant discussion on Angu ...

JavaScript utilizes regex patterns to modify the value located between the characters within an input's name attribute

Can anyone assist me in creating a unique regex pattern to extract specific characters from the attribute values of HTML inputs? I'm dynamically cloning select elements and input text with button clicks, so I need to maintain the attribute name synta ...

Please add color to the space beneath the line in a highchart

I have been tasked with customizing a line chart that was not originally created by me. The application pulls data from a database and organizes each element by hour before displaying it on the chart. When you hover over a point, the interface looks like t ...

The controller method in Laravel is not being triggered by AJAX

In my blade layout file, I have some code that is included in my view multiple times using the @include.layout("blade file link") syntax. When a button is pressed, I want to call a controller function. This works fine without AJAX, but when AJAX is added, ...

What steps can be taken to issue an alert when the table does not contain any records?

Upon clicking the submit button, the value from the database is retrieved based on the hidden field ID and displayed in a table. If the value is present, it should load in the table; otherwise, an alert saying 'there is no record' should be displ ...

What is the best way to modify the styling of my CSS attributes?

I'm currently working with this CSS code: input:checked + .selectablelabel .check { visibility: hidden; } Now, I want to change the visibility property to "visible" using JavaScript. I attempted the following: $(document).on('click', & ...

Is there a way to duplicate and insert a function in node.js if I only have its name?

I'm currently working on a code generation project and I've encountered a problem that I initially thought would be easy to solve. However, it seems to be more complicated than I anticipated. My task involves taking a method name as input, naviga ...

Adjust the body class dynamically based on the URL in AngularJS

Here is the link to my website To Log In - http://localhost/ang/#/login To Access Dashboard - http://localhost/ang/#/dashboard See below for the HTML code for the body tag If the current URL is http://localhost/ang/#/login, then the body should include ...

When I press the play button, the sound doesn't start playing

This is my script in action: <script> var audioObj = document.createElement("audio"); document.body.appendChild(audioObj); audioObj.src = "http://example.com/audios/Kalimba.mp3"; audioObj.load(); audioObj.volume = 0.3; audioO ...

Utilizing JavascriptExecutor to assign attribute based on name

When working with HTML that lacks an id and only has name, class, and tag attributes, it can be challenging to manipulate it using JavascriptExecutor. The name attribute is unique, while the other two attributes are common among various other elements in t ...

<a href> click here to append a new query parameter to the existing ones

Is there a way to create a link that will add a query parameter to the current URL instead of replacing all existing ones? Here's what I'm looking for: If the current URL in the browser is example.com/index.html, clicking on it should lead to ...

Issues with displaying images in Fancybox

I've integrated FancyBox into my website, but I'm experiencing a minor issue. While the FancyBox works perfectly in Dreamweaver, it seems to malfunction in various browsers. As someone who is not well-versed in programming, I'm struggling t ...

Encountering a NextJS error with head component

Trying to incorporate the head element into a NextJS page format has proven challenging. Despite consulting the official documentation, implementing next/head to add <head> has resulted in an error within the code block. Code: import Head from &apos ...