The scope.$apply function is not defined properly within the scrolly directive, causing it to not

Having trouble with the scrolly directive in my div. When the user scrolls down to the end of the div, I want to call a function. However, I'm getting 'undefined' when using Scope.$apply function. Can anyone help me out? Thanks in advance! Here is my HTML code:

 <div id="container"  style="
  position:absolute;
  top: 60px;
   width: 100%;
  left:0px;height:91%;overflow-y:scroll;" scrolly="showMore()" >

And here are the app and controller:

 var app = angular.module('smac',[]);
 app.controller('asd',function ($http,$scope) {
   $scope.showMore = function(){

     alert('div finished');
  }
  });

Lastly, here is the directive:

   app.directive('scrolly', function () {
return {
    restrict: 'A',
    link: function (scope, element, attrs) {
        var raw = element[0];
        console.log('loading directive');

        element.bind('scroll', function () {
            console.log('in scroll');

            console.log(raw.scrollTop + raw.offsetHeight >= raw.scrollHeight)
            if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
               scope.$apply(attrs.scrolly)

                console.log(scope.$apply(attrs.scrolly)); // this is undefined
            }
            });
    }
};
 });

Answer №1

It seems that the issue with your scope.$apply function returning undefined is likely due to the fact that your showMore function does not have a return value. When examining the $apply function in Angular's source code, you will find that it primarily calls the $eval function:

Snippet from Angular's Source Code

function $apply(expr) {
    try {
        return $eval(expr);
     } catch (e) {
         $exceptionHandler(e);
     } finally {
          $root.$digest();
      }
 }

If you refer to this Stack Overflow post about the functionality of $eval, you'll see how Angular evaluates expressions.

Therefore, the lack of a return value from your function may be causing the undefined result when using scope.$apply. This delves into why understanding the return value is important for your specific use case.

Answer №2

Remember to use $scope.$apply instead.

Don't forget the $ sign before scope.

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

Code for ajax request completed function

I am facing an issue with the following code: function loadRegions() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 ...

The current user's name is appearing as "undefined" in NextJS

Launching straight into the query, I am facing an issue when using console.log(user);. It returns an object with a string value for displayName. However, upon running console.log(user.displayName);, it should display the value Agrim Singh (<-- I've ...

Guide to utilizing a TypeScript declaration file for a different function

I'm a beginner in TS and I've created a definition file to specify the argument types for a function in another file. customFunctions.ts export default ({}) => { const myCustomFunction = ({ param1 }: { param1: string }) => { return ...

Navigate to a different HTML file following a JavaScript function in Ionic and AngularJS with Cordova

I am currently creating an Android application in Cordova Tools for Visual Studio using Ionic and AngularJS. My goal is to redirect to another HTML page once my function has completed its execution, but I'm having trouble getting it to work correctly ...

Why is my AJAX request not working in conjunction with my on-page JavaScript?

While working on an order confirmation page, I encountered a challenge with an AJAX request that I am making to a page containing JavaScript code for tracking cookies and recording data. Unfortunately, when the request is fired to this other page with the ...

using conditional statements in an app.get() method in express js

app.get('/api/notes/:id', (req, res, next) => { fs.readFile(dataPath, 'utf-8', (err, data) => { if (err) { throw err; } const wholeData = JSON.parse(data); const objects = wholeData.notes; const inputId ...

AngularJS is throwing an error of "TypeError: Cannot read property 'then' of undefined."

Within an AngularJS project, I am aiming to retrieve user data from those who sign in and utilize this data within an HTML form. To achieve this, I have a script called sessionService.js that sends requests to the server and receives responses. The follow ...

Is it possible to access the previous or next index in an array using ForEach in AngularJS?

$scope.todos = [ {text:'learn', done:true}, {text:'build', done:false}, {text:'watch', done:false}, {text:'destroy', done:false}, {text:'rebuild', done:false}]; $scope.remaining = fu ...

I keep getting an error message that says "The JSX element type does not have any construct or call signatures."

I am currently developing an application that takes user input through buttons and creates an array. However, when I attempt to display the array, I encounter a JSX element type error. import { Delete } from "lucide-react" export function Passwo ...

JavaScriptCore now includes the loading of AMD modules

I am trying to incorporate a JavaScript module into JavascriptCore on iOS. To achieve this, I am fetching the file's text through a standard HTTP request on the iOS platform. Once I have obtained the entire string, I plan to parse it into the JSconte ...

What is preventing qUnit from sending notifications for exceptions within a frame?

When using qUnit, I've noticed that it doesn't provide any indication when an exception occurs in a later part of the test. For example, running the following code within a test(): stop(); function myfun(ed) { console.log('resumed' ...

Utilize CDN-sourced library within an Angular component

I've been attempting to connect with the HelpScout beacon using their API methods but am struggling to access the DOM from the controller. I have experimented with functions like document.HS.beacon.ready(function() { // Open the Beacon as soon as ...

Unusual class exhibiting peculiar async/await patterns

Node 7.9.0 The situation goes like this: class TestClass { constructor() { const x = await this.asyncFunc() console.log(x) } async asyncFunc() { return new Promise((accept) => { setTimeout(() => accept("done"), 1000) }) ...

Determine the precise x and y coordinates of a centered element using JQuery

How can I determine the exact left and top positions of an element? The parent container has text-align: center, causing potential confusion when there are multiple elements on the bottom row. For instance, the first one may have a position of 0px instea ...

Error encountered when attempting to embed a SoundCloud player in Angular 4: Unable to execute 'createPattern' on 'CanvasRenderingContext2D' due to the canvas width being 0

I attempted to integrate the SoundCloud iframe into my Angular 4 component, but encountered the following error message: Failed to execute 'createPattern' on 'CanvasRenderingContext2D': The canvas width is 0. Here is the iframe code ...

Load link dynamically using the rel attribute

I am trying to implement dynamic content loading using jQuery's .load() function. The links are stored in the .rel attribute of the anchor tags. My setup looks like this: <script> $(document).ready(function(){ $('.sidebar_link').clic ...

Troubleshooting Typescript app compilation problem in a Docker environment

I am encountering a challenge while trying to build my typescript Express app using Docker. Surprisingly, the build works perfectly fine outside of Docker! Below is the content of my Dockerfile: FROM node:14-slim WORKDIR /app COPY package.json ./ COPY yarn ...

What is the best way to dynamically pass a service to a controller based on specific conditions?

Utilizing the ui-router module, I have defined two states: .state('projects.create', { url: '/create', views: { 'outer@': { templateUrl: 'views/projects.create ...

What is the best way to pass a file and a string to my C# backend using JQuery Ajax?

I have a user interface with two input fields - one for uploading a file and another for entering the file's name. I need to capture both the file (as binary data) and its corresponding name in a single AJAX request, so that I can upload the file usi ...

The server is throwing a 403 error when trying to submit an AJAX request

I am currently working on a project similar to jsfiddle and encountering an issue during development. Whenever I attempt to make an ajax request with the JS alert() function in a text box, the server is returning a 403 error. Can anyone provide assistance ...