When Controller Scope Goes Missing in ng-repeat

Upon glancing at my code, it should be evident that I am a newcomer to the world of Angular.

I am currently developing an application that enables users to search for text, queries a database whenever the value in the text input changes, and displays a list of matches. The backend is straightforward and operational. On the frontend, I have implemented the search field and the results container:

<div id="search" ng-controller="FormController">
    <input type="text" class="form-control input-lg" placeholder="Start typing . . ." ng-keypress="search()" ng-model="searchField" id="search-field">

    <div id="results" class="alert alert-success">
        <a href="#" ng-href="#" ng-repeat="item in items" ng-click="add(item)">
            <p class="lead text-left">
                <span>{{item.DisplayName}} -</span>
                <span> {{item.Description}} -</span>
                <span> {{item.Count}} ct. -</span>
                <span> ${{item.Price}}</span>
                <span class="glyphicon glyphicon-check pull-right"></span>
            </p>
        </a>
        <h4>{{noResults}}</h4>
    </div>
</div>

Two methods are called within my controller:

$scope.search = function()
{
    $scope.$watch('searchField', function (newValue)
    {
        if (newValue)
        {
            $http.post('/search', 
            {
                val: newValue
            })
            .success(function (response)
            {
                if (response.length > 0)
                {
                    $scope.items = response;
                    $scope.noResults = '';

                }
                else 
                {
                    $scope.noResults = 'No Matches Found';
                    $scope.items = '';
                }
            })
            .error(function (response)
            {
                console.log('Oooops, error: ' + response);
            });
        }
    });
};

$scope.add = function(item)
{
    console.log('added');
};

$scope.search() is functional but add() method does not trigger on click. It seems like I may not be within the scope of the controller at that point. Despite extensive research, I am stuck and seeking assistance. I have reached the frustrating "banging-your-head-against-the-keyboard-and-hopint-for-it-to-magically-work" phase.

Could this possibly be related to an inheritance issue?

** Update ** Here is the complete controller (with the $watch removed as suggested in the comments):

var app = angular.module('AppModule', ['toastr']);

app.controller('FormController', ['$scope', '$http', 'toastr', function($scope, $http, toastr)
{

    $scope.search = function()
    {
        var searchText = $scope.searchField;

        $http.post('/search', 
        {
            val: $scope.searchField
        })
        .success(function (response)
        {
            if (response.length > 0)
            {
                $scope.items = response;
                $scope.noResults = '';

            }
            else 
            {
                $scope.noResults = 'No Matches Found';
                $scope.items = '';
            }
        })
        .error(function (response)
        {
            console.log('Oooops, error: ' + response);
        });
    };

    $scope.add = function(item)
    {
        console.log('added');
    };

}]);  

Update 2

Here is a plunker demonstrating that everything works up until the add() method (which may have been renamed). Instead of my $http post, I have hardcoded a simulated response from the server.

Answer №1

Dealing with a CSS problem? Try commenting out line 8382 in your stylesheet (specifically the code that sets #results to display as none). Once you do this, the issue should be resolved. However, how you choose to address this in your CSS moving forward is another matter.

Answer №2

After reviewing your plunker, it appears that the issue I found was quite trivial.

Initially, I tried removing the class has-value from resultsContainer using a timeout, which resolved the issue with addItem.

  setTimeout(function() {
      resultsContainer.removeClass('has-value');
  }, 1000);

While this approach may work, I realized that utilizing setTimeout is not ideal.

Upon further exploration, I discovered that the problem stemmed from using display:none for #results. I decided to remove the display CSS property and utilize opacity instead.

    #results {
      position: absolute;
      /*display: none; */
       opacity : 0; 
      top: 100%;
      left: 0;
      width: 100%;
    }
    #results.has-value {
      display: block;
       opacity : 1;
    }

This adjustment resolved the issue without the need for a timeout. **I have encountered similar issues in the past where using display:none caused functionality problems. It's important to either adjust your CSS or use a timeout as an alternative solution.**

Additionally, I recommend considering moving that code into a directive for better organization.

You can view the updated plunker here

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

Deploying an Azure Blob Trigger in TypeScript does not initiate the trigger

After successfully testing my Azure function locally, I deployed it only to find that it fails to trigger when a file is uploaded to the video-temp container. { "bindings": [ { "name": "myBlob", "type&qu ...

Storing items in localStorage in the same order they were added

I am having an issue with sorting localStorage items by the order they were added. Despite my code working to add items to the localStorage array and display them as HTML, I am encountering a problem with the order of the items. When I add a 3rd item to t ...

The expected React component's generic type was 0 arguments, however, it received 1 argument

type TCommonField = { label?: string, dataKey?: string, required?: boolean, loading?: boolean, placeholder?: string, getListOptionsPromissoryCallback?: unknown, listingPromissoryOptions?: unknown, renderOption?: unknown, getOptionLabelFor ...

Unable to bind to property as it is not recognized as a valid attribute of the selector component

I have a situation where I need to pass a variable from one component to another using @input. Here is my parent component : @Component({ selector: 'aze', templateUrl: './aze.component.html', styleUrls: [('./aze.compo ...

Leveraging AngularJS directives and $scope autonomously

Let me provide some context first: Previously, my focus was on developing lightweight, single-page Angular applications. However, in the past few days, I began working on a new project that combines Tapestry and Backbone. It has proven to be quite overwhe ...

Converting an array of object values to an Interface type in Typescript

In my JSON document, I have an array named dealers that consists of various dealer objects like the examples below: "dealers" : [ { "name" : "BMW Dealer", "country" : "Belgium", "code" : "123" }, { "name" : ...

Tips for escaping an infinite loop within the componentDidUpdate function in reactjs

Currently, I am working on creating dashboards using reactjs. I have successfully implemented 4 tabs or buttons for charts, but I am facing an issue when clicking on different dashboards that have the same chart in the same panel. The chart is not updating ...

Obtaining the data stored in objects within a parse database

I'm currently facing an issue where I am trying to retrieve the name of the creator from the session object, which is a pointer. For testing purposes, I have been attempting to access this information but it keeps showing up as undefined. Any suggesti ...

Attempting to manipulate information within the @click event handler embedded within a v-for loop

I am using a v-for loop to select dialog boxes that I want to open. <v-card @click="page.model = true"> In this code, page.model is being used as the v-model for a v-dialog component. data() { return { dialog1: false, dia ...

Looking for jQuery bbq... is the grill fired up yet?

In my exploration of the jQuery bbq plugin, I noticed that there is no reference to document.hash in the code. I believe that the function for retrieving the hash is located at line 1094: function get_fragment( url ) { url = url || location.href; ...

Discovering the final element of ng-content while conducting tests using Protractor

I am searching for the always last element to click on. This is what I see when I inspect the page. ...

Can express-handlebars tags be utilized within an HTML script tag when on the client side?

For a while now, I've been facing a challenge. I'm in the process of building an application with express-handlebars and so far everything is going smoothly. The data that needs to be displayed on the webpages looks good thanks to the Helper func ...

Angular 6+ Unveiled: The Magic of Transparent Wrapper Components

One standout feature of Vue.js is the ability to dynamically assign new attributes to a specific element within the template, which is referred to as Transparent Wrapper Components In this example, I am able to pass all existing HTML attributes to a speci ...

Do JavaScript Promises operate asynchronously?

Can we clarify if JavaScript Promise is asynchronous? I've been researching Promise and async programming, particularly with ajax requests. If Promise isn't inherently async, how can we make it so? For instance, consider a function that encapsul ...

The checkbox click function is not functioning properly when placed within a clickable column

In my coding project, I decided to create a table with checkboxes in each column. <table class="bordered"> <thead> <tr style="cursor:pointer" id="tableheading" > <th>Name ...

Does ng-bind have the ability to function with input elements too?

My mind was spinning as I tried to figure out why my <input ng-bind="x.a * x.b" tabindex="-1" readonly/> expression wasn't functioning. The use of ng-model was not an option due to the fact that the product is not an L-value, so I made the swi ...

Issue with integrating Google Spreadsheet as the data source for a Next.JS website: updates are not reflecting on the website pages

The website for this restaurant was created by me, using Google Spreadsheet to populate the menu pages. I chose this method for its simplicity and familiarity to the client. I'm utilizing the google-spreadsheet package to extract necessary informatio ...

Custom condition in NG-STYLE fails to trigger

Here is a simplified representation of an item in a remote datasource: [ { "id": "3", "card_name": "Free Beer!", "count": "1" } You have a DIV with an NG-REPEAT, also simplified: <div ng-repeat="card in cardDetails"> <h1>{{card. ...

The ability to submit a conversation chat is currently

I encountered an issue when attempting to submit a chat, and I received the error message 'handlebar is not define'. I followed the code tutorial provided in this link: https://codepen.io/drehimself/pen/KdXwxR This is the screenshot of the error ...

Ways to delete a document from Mongodb depends on the existence of a more recent document

Is there a way to automatically delete previous database insertions in my meteor web app whenever a new document is inserted? I've attempted the following code, but it hasn't been successful: if(SearchLobby.find({profile: Meteor.userId()}).count ...