In the context of a controller, a directive with an isolate scope does not automatically update when a new element is added

I am currently working on implementing a basic recent searches list feature on my website. The idea is that when the user clicks on the search button, two inputs are combined and added to an array named "recentSearchItems". However, despite updating this array in the homeCtrl, the changes are not reflected in the directive.

Here is the code snippet from index.html:

<body ng-controller="HomeCtrl">
<div class="outer-wrapper">
    <div class="main-wrapper" ng-class="{'search-page': searchClicked}" ng-show="uiRouterState.current.name == 'home'">
        <div class="home-logo" ng-class="{'animate': searchClicked}">
        </div>
        <div class="home-content-wrapper" ng-class="{'animate': searchClicked}">
            <div class="main-header" ng-class="{'animate': searchClicked}">
                Lorem ipsum dolor sit!
            </div>
            <div class="main-large-text" ng-class="{'animate': searchClicked}">
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
            </div>
            <form class="form-elements">
                <input type="text" class="large-textbox" name="looking-for" placeholder="I am looking for" ng-model="placeKeyword">
                <input type="text" class="medium-textbox" name="place" placeholder="Istanbul" ng-model="placeNear" style="margin-left: 10px;">
                <button ui-sref="home" class="search-btn" style="margin-left: 10px;" ng-click="startSearch()">
                    <span></span>
                </button>
            </form>
        </div>
    </div>
    <div ui-view></div>
    <div class="footer-wrapper">
        <div class="footer-links">
            <a href="#">About us</a>
            <a href="#">Contact</a>
            <a href="#">Blog</a>
        </div>
    </div>
</div>
</body>

The content html (to replace the "ui-view" directive) looks like this:

<div class="search-items" ng-show="uiRouterState.current.name == 'home'">
    <div class="places-list">
        <place-grid ng-repeat="place in places"></place-grid>
    </div>
    <recent-searches recent-search-items="recentSearchItems"></recent-searches>
</div>

Snippet from homeCtrl:

placesApp.controller("HomeCtrl", ["$scope", "$state", "FoursquareApiService", ($scope, $state, FoursquareApiService) => {
    $scope.uiRouterState = $state;
    $scope.searchClicked = false;
    $scope.recentSearchItems = [];

    $scope.startSearch = () => {
        if($scope.placeNear) {
            $scope.addToSearchHistory($scope.placeKeyword, $scope.placeNear);
            $scope.searchClicked = true;

            var promise = FoursquareApiService.getPlaces($scope.placeNear, $scope.placeKeyword);
            promise.then(
                function(response) {
                    $scope.places = response;
                },
                function(error) {
                    console.log("Couldn't get the places data: " + error)
                }
            );
        }
    };

    $scope.addToSearchHistory = (placeKeyword , placeNear) => {
        $scope.recentSearchItems.push(placeKeyword + " in " + placeNear);

    };

}]);

Directive section:

placesApp.directive("recentSearches", () => {
    return {
        restrict: "E",
        replace: true,
        scope: {
            recentSearchItems: "="
        },
        templateUrl: "views/recent-searches.html"
    }
});

Template for the directive:

<div class="recent-searches">
    <h3>RECENT SEARCHES</h3>
    <hr class="under-header">
    <div class="recent-search-items" ng-repeat="recentSearchItem in recentSearchItems">
        <p ng-bind="recentSearchItem"></p>
        <hr>
    </div>
</div>

Answer №1

Include bindToController: true in your directive definition.

placesApp.directive("recentItems", () => {
    return {
        restrict: "E",
        replace: true,
        scope: {
            recentItemsList: "="
        },
        templateUrl: "views/recent-items.html",
        bindToController: true
    }
});

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 parameter issues while working with Google Maps React in TypeScript

Currently, I'm utilizing TypeScript in this particular file. import React, {Component} from 'react' import {Map, InfoWindow, Marker, GoogleApiWrapper, mapEventHandler, markerEventHandler} from 'google-maps-react'; import { coordina ...

Prevent users from changing dropdown options after a form submission fails using Javascript and Jquery

Currently, I am pursuing the tech degree at Team Treehouse and my third project involves creating an interactive form. To simplify my issue, I will outline it in bullet points: The credit card payment method should be preselected when the page loads. I n ...

Jquery problem: dealing with empty spaces

I am working on a project where I need to use jQuery to disable specific input fields, like the following: $("input[value=" + resultId[i].name + "]" ).prop('disabled', true); $("input[value=" + resultId[i].name + "]" ).css({ 'background-col ...

What's the best way to establish a victorious player in a game of Tic

I've been struggling to find a solution for determining the winner using WinCombos. Is there a way to compare the elements in my winCombos array with the cells of a 3x3 tic tac toe board to identify the winner? var player1 = "X"; var player2 = "O"; ...

The background gently fades away, directing all attention to the popup form/element

After extensive searching, I have yet to find a straightforward solution that seems to be a standard practice on the web. My goal is to create a form that appears in the center of the screen when a button is clicked using CSS or jQuery. I would like the ...

Tips on creating a responsive absolute div

I'm currently working on creating a profile component with Material UI and React.js. I'm having trouble making the Avatar/profile photo and profile name div responsive. Here are some screenshots to illustrate my issue: The specific div that need ...

Ways to update status in intervals of x seconds

I am trying to update the name of every avatar automatically every X seconds. I found a helpful solution that works well, but currently it is displaying the same name for all avatars from the RandomAcidName array. I believe I need to iterate through this ...

Problem with the show/hide feature on jQuery. Automatically scrolls to the beginning of the page

On my website, I have successfully implemented two basic Show / Hide links that are working great. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" conte ...

The Angular carousel fails to display or operate properly

I am encountering an issue where the content is not displaying when using the angular-carousel directives: <ul rn-carousel rn-carousel-controls rn-carousel-index="carouselIndex" rn-carousel-buffered > <li ng-repeat="slide in slides track by ...

What is the best way to manage the "checked" state of an input checkbox using React?

I'm currently developing an application that features a form with radio buttons. One of the radio button options can be toggled on/off using a checkbox, but I want to ensure that the checkbox is disabled if the corresponding radio button is not selec ...

Using the Angular two-way binding tag within a Spring Boot Thymeleaf application allows for seamless data synchronization between

I have a JSON file where my image is defined like this certLogoURL : "/img/ocjp.gif" I am attempting to show this image in my Thymeleaf template using the following code: <img th:src="@{ {{certificate.certLogoURL}} }" > </img> However, the ...

Eliminate the need to input the complete URL every time when making server calls

Currently, my springbok application has a React-Typescript frontend that is functioning well. I am using the request-promise library to make requests like this: get('http://localhost:8080/api/items/allItems', {json: true}). However, I would like ...

Retrieving a specific data point from the web address

What is the most efficient way to retrieve values from the window.location.href? For instance, consider this sample URL: http://localhost:3000/brand/1/brandCategory/3. The structure of the route remains consistent, with only the numbers varying based on u ...

Storing specific items in an array for easy access on the following page

I have some code that extracts specific keys and values from a row and then sends them to the next page. let HistoryData = []; for (const [key, value] of Object.entries(this.Items)) { HistoryData.push(value) } this.$router.push( ...

Experiencing difficulties accessing Facebook using ngFacebook on angularjs application

I've been working on implementing ngFacebook login into my Angular app, but I'm facing an issue with logging in to Facebook. Even after calling '$facebook.log()', nothing is being displayed in the console. This is a snippet of my Angul ...

Is there a method to determine whether the user has granted permission for notifications to be enabled?

Once I have requested permission from the user of the website, I need to confirm if they have granted permission before triggering the send() function. What is the most sophisticated approach to achieve this? ...

Tips and tricks for bypassing the annoying "save as" popup while downloading files remotely using SauceLabs

Running a protractor spec from a Jenkins job, connecting to SauceLabs to click a button for downloading a PDF file, and verifying the successful download. Struggling to prevent the chrome browser from displaying a "Save As" prompt when using an absolute pa ...

Obtain geographic information using a JSON fetch from a map

I am facing an issue while integrating Laravel API data into React. Although I can see the JSON data in the console after fetching it, I encounter an error when I try to display it in a table for listing. The error states that my .map function is not recog ...

Various SVG paths make up segments

I have created an intricate SVG file containing 35 different paths resembling train tracks. My next step is to break down these paths into 16 segments, allowing another SVG path (train) to smoothly traverse along them. The ultimate goal is to grant users ...

The name field in the request body is currently undefined

Currently, I am working on developing a basic blog page using technologies such as ejs, JavaScript, Node.js, Express, and body-parser. While working on passing inputs to the command line, specifically for the title, I encountered an issue. When I used req ...