AngularJS - Array binding issue not updating in directive

I am currently developing a directive that has the ability to display a series of controls.

Each individual control is implemented as a directive named fsFilter. In the controller managing the parent element, I establish a binding between the filters array and an array in the parent scope.

Initially, this process works smoothly and upon the first compilation of the directive, it renders the child directives successfully.

However, when I introduce a new object into the filters array within the parent scope, I can observe through $watch that the connected array within the child scope has been modified. Yet, the alteration in the property does not trigger a recompilation. Despite attempting to utilize $apply and implementing an addFilter method within the directive's scope - even resorting to somewhat unconventional measures like invoking element.scope() directly - the array gets updated but the recomposition remains elusive. Even executing $apply following the addition of a new object to the array proves ineffective.

Below is my directive:

.directive('fsFilterCollection', function ($compile, $timeout) {
    return {
        restrict: 'AE',        
        priority: 1002,
        scope: {
            filters: "="           
        },
        controller: function ($scope, $element, testFactory) {
            $scope.filterIndex = 0;

            $scope.filterClosedFn = function ($event, filterdata) {
                $event.stopPropagation();
                $scope.filters = $scope.filters.filter(function (el) { return el.name != filterdata });
                console.log("filter closed" + testFactory.sayHello());
            }

            if ($scope.filters) {
                angular.forEach($scope.filters, function (el) { el.index = $scope.filterIndex++; });
            }

            $scope.addFilter = function () {  
                if (arguments.length == 1 && angular.isObject(arguments[0])) {
                    $scope.filters.push(arguments[0]);
                }
                else {
                    $scope.filters.push({ filterType: "String" });
                }             
            }
        },
        template: function (element, attr) {
            return '<div>'+
                    '   <div ng-repeat="filter in filters">'+
                    '     <div>',
                    '          <div fs-filter keepopen="true" filter-closed-fn="filterClosedFn" isopen="isopen" keepopen="true" filterdata="filter.filterdata" fs-filter actions="true" filter-type="String"></div>' +
                    '       </div>'+
                    '   </div>'+
                    '</div>'
        },
        link: function ($scope, element, attrs, ngModelController) {

            $scope.$watch('filters', function () {
                // reindex
                $scope.filterIndex = 0;
                angular.forEach($scope.filters, function (el) { el.index = $scope.filterIndex++; });
            },true);
        }
    }
})

This snippet showcases my parent controller:

var myAppModule = angular.module('development-beta', ['ui.select', 'ui.bootstrap','firespace.filtercontrol','ngSanitize']);
myAppModule.controller('fs-controller', ['$scope', function ($scope) {

    $scope.filters = [
        { filterType:"String" }
    ];            

    $scope.addFilter = function () {
        $("#myfilters *[fs-filter]").scope().addFilter();
    }
}]);

Furthermore, I would greatly appreciate any insights on whether updating the bound array in the parent scope represents the correct approach for this task. I have considered utilizing a factory, but due to its singleton nature, I am uncertain how to manage each directive's scope without passing the $scope into every call?

Thank you for any guidance provided.

Answer №1

Feeling under the weather today.

If you're experiencing issues with ng-repeat not binding, there's a chance it could be related to...

 template: function (element, attr) {
            return  '<div>'+
                    '   <div ng-repeat="filter in filters">'+
                    '     <div>',
                    '          <div fs-filter keepopen="true" filter-closed-fn="filterClosedFn" isopen="isopen" keepopen="true" filterdata="filter.filterdata" fs-filter actions="true" filter-type="String"></div>' +
                    '       </div>'+
                    '   </div>'+
                    '</div>'
        },

I made a mistake in my code by using a ',' instead of '+' in the template (LINE 4)

This solution might come in handy for someone in the future.

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

I am having an issue with the npm install command. Each time I try running it, I keep receiving an

After posting the output, I find myself unable to comprehend anything. Can someone please guide me on what steps to take next? npm has issued a warning about an old lockfile and advises that supplemental metadata needs to be fetched from the registry due t ...

Utilizing express.js alongside the native MongoDB driver: A comprehensive guide

I'm facing difficulties when attempting a simple mongoDB query from my express app: app.js var express = require('express'); var routes = require('./routes'); var user = require('./routes/user'); var http = re ...

Update breadcrumbs dynamically by clicking on each horizontal panel

I've been dealing with a problem for the past 24 hours. I want to implement a horizontal accordion with breadcrumbs on a webpage. How can I achieve this dynamically, so that when a user clicks on any link in the accordion, the breadcrumbs update simul ...

Subtracting 25% from the width of the web browser

After spending some time trying to solve this issue by myself, I've decided to reach out for help here where I know I can get some great responses. I am looking to determine the dimensions of the browser window minus 25%. Specifically, I have a two-c ...

What could be causing my CSS navigation toggle button to malfunction?

My attempt at creating a toggle button for tablets and phones seems to be failing. Despite the javascript class being triggered when I click the toggle button, it is not functioning as expected... https://i.stack.imgur.com/j5BN8.png https://i.stack.imgur. ...

Obtaining template attributes in CKEditor: A guide

I have been working with the template plugin in CKEditor to load predefined templates. Each template is defined as follows: templates: [ { title: "Quickclick 1", image: "template1.png", description: "Quickclick 1 template", html_et: "& ...

How can AJAX be used to execute a PHP script that deletes a record from a database table?

Yesterday, I asked for help on how to save user-generated blog posts and I successfully tackled the database aspect of it. Now, my next goal is to be able to delete a blog post upon clicking a button with an onclick event. After researching extensively onl ...

Issue with ng-repeat directive not functioning

Let's dive into this directive: .directive('img', function () { return { restrict: 'E', link: function (scope, elem, attr) { if (attr.src && attr.type === "extension"){ var ...

How to convert a string of comma-separated values into an unordered list using ng-repeat in AngularJS

In my code snippet, I am utilizing an array named data.list to store mandatory and optional appointments. data.list.push({ mandatory: appt.getDisplayValue('mandatory_appointments'), optional: appt.getDisplayValue('optional_appointments& ...

The functionality of the OnClientClick event within the ASP.NET platform

While utilizing ASP.NET to pass a value to a JavaScript function, I encountered an issue where it doesn't seem to work when trying to pass a value from another control. It seems to behave as if there is a syntax error and just reverts back to the main ...

Positioning tooltip arrows in Highcharts

I'm attempting to modify the Highcharts tooltip for a stacked column chart in order to have the arrow on the tooltip point to the center of the bar. I understand that I can utilize the positioner callback to adjust the tooltip's position, but it ...

Looping through a Vue Bootstrap modal using a v-for directive

I am working on a Vue Bootstrap modal placed within a v-for loop. I need to replace the '1' in both 'v-b-modal.modal-1' and 'modal-1' with the index value, which I can access as {{ index }} while looping through the items. How ...

No Backend Detected for Tensorflow.js in Node

I've been attempting to develop a Discord bot that utilizes the @tensorflow-models/qna library, but I've hit a roadblock for the past 4 hours. Every time I run the script below: const qna = require('@tensorflow-models/qna'); (async () ...

Is there a way to transfer HTML code from a textarea to CKEDITOR for setData?

My goal is to retrieve data from a textarea element and use it as setData for CKEDITOR. However, instead of receiving the HTML code, I am only getting the code as a string, which is not rendering properly as HTML. Here's the code snippet: CKEDITOR.re ...

Inspect the key within a complex hierarchy of nested objects in an array

I am working with an array of nested objects and need to extract the value of a specific key property. Currently, I am using a for loop and checking for the existence of children property, but I feel there might be a more optimal way to accomplish this tas ...

When utilizing a Javascript event listener within ReactJS with NextJS, the dynamically imported module without server-side rendering fails to load

Hello everyone, I am new to ReactJS and NextJS and would really appreciate some advice on the issue below. Thank you in advance! Here is my current tech stack: Node v16.6.1 React v17.0.2 Next.js v10.0.4 I'm working on implementing a carousel and si ...

Discovering the version of the Javascript library utilized on a website - a step-by-step guide

My quest is to uncover the versions of JavaScript libraries being utilized by popular websites. By using phantomjs.exe, I successfully identified the version information for jquery. However, I am currently at a loss on how to expand this capability to inc ...

Installing external Javascript libraries on Parse cloud code can be done by following these steps

Currently, I have integrated these JavaScript libraries into my Parse cloud code. var request = require('request'); var fs = require('fs'); var Twit = require('twit'); However, the code refuses to compile if these libraries ...

Unable to insert a JSON object into an Array

This might appear to be a duplicate, but it's not. None of the solutions I've tried have worked. Within my angular module, I have a list: this.checkedInterviews = [] Followed by a function that does the following: var interviewModel = { ...

Angular URL rewriting for optimal performance

Is it possible to rewrite an Angular URL like "www.mycompany.com/employee/{78}" so that when clicking on the employee and trying to open it in a new tab, it uses the base URL "www.mycompany.com/index.html/employee/78"? <rule name="main rule 2" stopProc ...