Angular component featuring an array of information

I have developed a custom directive

app.directive('projects', ['projectServices',
    function(projectServices) {
        var projectController = function() {
            var proj = this

            projectServices.getProjects()
                .success(function(result) {
                    proj.projects = result.data

                    proj.projects.map(function(project) {
                        project.showDetails = false
                    })
                })
                .error(function(err) {
                    console.log('error ' + err)
                })

            this.toggleProjectDetails = function(project) {
                project.showDetails = !project.showDetails
            }

        }

        return {
            restrict: 'E',
            templateUrl: '/partials/project',
            controller: projectController,
            controllerAs: 'projectCtrl'
        }
    }
])

The template layout is as follows

div(ng-repeat='project in projectCtrl.projects')
p(style='margin-bottom:0px') {{project.title}}
span.italic {{project.start_date | date}} - {{project.end_date | date}}
p {{project.abstract}}
    a.btn-xs(style='color:black' ng-click='projectCtrl.toggleProjectDetails(project)')
        i.fa.fa-angle-double-down
p(ng-show='{{project.showDetails}}') {{project.details}}

The projects data structure looks like this:

[{
"title" : "Project Title",
"abstract" : "Brief description of the project",
"details" : "Lorem ipsum blah blah blah",
"start_date" : ISODate("2014-07-02T11:07:34.000Z"),
"end_date" : ISODate("2014-07-02T11:07:34.000Z"),
"links" : [ 
    {
        "title" : "link name",
        "url" : "www.google.com"
    }
   ]         
},...]

The issue I am facing is that when I trigger the toggleProjectDetails function, it executes successfully but the corresponding section of the page is not updated. It seems like the ng-show is not being re-evaluated.

Can anyone help me identify what's missing in my setup?

You can view a demo through this Plunker link.

Answer №1

Finally managed to solve the issue with a lot of troubleshooting using your provided plunker. I made changes to the project.details in the toggle method and that did the trick. Additionally, I found and fixed the ng-show bug.

It was discovered that the ng-show directive should not include double curly braces {{}}. So instead of

p(ng-show='{{project.showDetails}}') {{project.details}}

it should be written as follows:

p(ng-show='project.showDetails') {{project.details}}

With that adjustment, the problem was resolved successfully.

Answer №2

After overcoming the challenge at hand, I devised a solution by implementing a controller for the array. This controller managed the service and added individual controllers for each element within the array. This is how my code now appears:

The Controller and Directive responsible for managing the projects retrieved from the server:

app.directive('projects', ['projectServices',
    function(projectServices) {
        var projectController = function($scope) {

            projectServices.getProjects()
                .success(function(result) {
                    $scope.projects = result.data
                })
                .error(function(err) {
                    console.log('error ' + err)
                })
        }

        return {
            restrict: 'E',
            templateUrl: '/partials/project',
            controller: projectController,
            controllerAs: 'ProjectListController'
        }
    }
])

The individual Controller for each project:

app.controller("projectController", ["$scope",
    function($scope) {
        $scope.project.shDetails = false;

        $scope.toggleDetails = function() {
            $scope.project.shDetails = !$scope.project.shDetails
        };

        $scope.showDetails = function() {
            return $scope.project.shDetails
        }
    }
])

Furthermore, here is the modified template reflecting these changes:

div(ng-controller="projectController" ng-repeat='project in projects')
    p(style='margin-bottom:0px') {{project.title}}
    span.italic {{project.start_date | date}} - {{project.end_date | date}}
    p {{project.abstract}}
    a.btn(style='color:black' ng-click='toggleDetails()') 
        i.fa.fa-angle-double-down
    p(ng-show='showDetails()') {{project.details}}

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

jQuery parent() Function Explained

checkout this code snippet - https://jsfiddle.net/johndoe1994/xtu09zz9/ Let me explain the functionality of the code The code contains two containers: .first and .second. The .first container has two default divs with a class of .item. The .second contai ...

The angular js routing and translate template is malfunctioning and not functioning as expected

Just delving into the world of Angular and finding it quite fascinating! I'm currently designing a template for a promotional page but running into an issue - half of my script seems to have stopped working... If you'd like to take a look, here ...

HTML5 validation fails to activate

Addressing the issue head-on Check out the form I have created: <form action="<?php echo base_url()?>" method="post" id="formfield"> <center> <label>How much? <small>( Minimum of 100 )</small></label&g ...

PhantomJS Alert: UnresolvedPromiseRejectionNotice

My main objective is to extract data from a website using Node.js. I have successfully managed to gather information using the request package, however, the website I am targeting contains dynamic content which cannot be accessed solely with request. Aft ...

When an item in the accordion is clicked, the modal's left side scroll bar automatically scrolls to the top. Is there a solution to prevent this behavior and

When I first load the page and click on the Sales accordion, then proceed to click on Total reported and forecasted sales, the scrollbar jumps back up to the top The marked ng-container is specifically for the UI of Total reported and forecasted sales He ...

Applying a CSS class to a newly generated row with JavaScript

I have a JSP page where I dynamically add rows to a table using a different Javascript function than in my previous query. While I can add elements to the table columns, I'm unable to apply a style class that is defined in a CSS file. Here is my Java ...

HTML - lunar phases - update link based on user interaction

Reason: I am aiming to include tide times on my website as a minor feature rather than the main focus. Objective: As part of this tide times feature, I want to offer users a dropdown menu to choose a location and have the default tide times update based o ...

Can the chrome console be used to showcase the contents of objects?

When I have a line of code, and I try to output it to the console, I only see [object Object] instead of the actual object types. console.log(`%c ${args[args.length-1]} ${performance['now'](true, args[args.length-1])} [(${args.slice(0, args.leng ...

When you select the checkbox button, a textfield and submit button will appear. Once you click the submit button, the checkbox button will be disabled

<td> <input type="checkbox" ng-model="alert.acknowledged" ng-disabled="alert.acknowledged" ng-click="onacknowledgedClick(alert)"></td> <td> <span ng-if="!alert.acknowledgeInProgress">{{alert.acknowledgedComments}}</span&g ...

The stubborn Node and Passport are refusing to update the password using user.setPassword

Currently, I am working on setting up my program to update a user's password only when the old one is confirmed as correct. Most of the code functions as expected except for one specific line: router.put("/:id/edit_password", isLoggedIn, isAdministra ...

Adding an extra element to the <MuiThemeProvider /> causes the page to display as blank with no error notifications

After incorporating Material UI into my Meteor application via npm install --save material ui I successfully implemented the <Header /> component in my app.js file. However, when I try to add additional components, such as localhost:3000, all I see ...

Issue with AngularJS dropdown visibility on Internet Explorer 9

After testing the code below in Chrome and confirming it works, I encountered issues when trying it in IE9. Despite upgrading my AngularJS version to v1.2.16 along with angular.min.js, the dropdown results still wouldn't show up. <div id="ng-app" ...

Tips for uploading a React component along with its static assets to npm

As I work on a React component that I plan to publish on npm, I've encountered an issue with distributing static assets like css and images alongside the component. While sources must be transpiled to plain js and css, finding best practices for this ...

What could be causing my project to install an erroneous Angular version?

It appears that my project is not utilizing the latest Angular code, but I am unsure of the reason behind this. I have checked my package.json file and found the following dependencies: "devDependencies": { "@angular/common": "2.0.0", "@angular ...

Automatically populating fields in Laravel 8 after selecting a value from a dropdown menu

Having an issue once again.. If I choose the Banjarmasin-Jakarta route, the shipping cost field will be filled with 1.750.000 However, if I want to select "search shipping route" again, the shipping cost field will be filled with 0 Select "search shippi ...

Using the match.params.id in React: A step-by-step guide

Having some trouble with my React code. I need to display the product name based on its ID, where the product data is fetched from product.js. I am using a router to switch between different products without reloading the page. import product from './ ...

Looking to resolve an issue that is arising in the antd tree component

Having trouble with the antd tree component - when searching and checking/unchecking a field, all previously selected data is unchecked. I want to only update the field that is currently being changed. Not sure how to fix this issue, any help would be appr ...

What is the most effective method for identifying the initial timestamp for each day, week, or month within a collection of timestamps?

I am dealing with a lengthy array of sorted timestamps representing stock price quotes. These timestamps have minimal resolution, meaning that each timestamp is at least 1 minute bigger than the previous one. However, there can be gaps during the day, espe ...

What is the best location to insert JavaScript from a website template into a Blazor project?

I recently set up a new Blazor WebAssembly project in Visual Studio 2019 and wanted to integrate a website template. After downloading the template, I am unsure where to place the accompanying JavaScript files. Currently, I have placed them within my inde ...

Struggling to get JavaScript to successfully load a .txt file in order to load various links

I created a cool feature that takes users to a random link, but I currently have a large list of links and wanted to find a way for JavaScript to read them from a text file. The code I have tried so far is not working, and I have experimented with other s ...