Embedding an Angular function within a JavaScript function

My AngularJS dialog is defined in the angular-app.js file like this:

angular.module('myAPP', ['ngMaterial']).controller('AppCtrl', function($scope, $mdDialog) {
    $scope.status = '  ';
    $scope.showAdvanced = function(ev,_url) {
        $mdDialog.show({
            controller: DialogController,
            templateUrl: _url,
            parent: angular.element(document.body),
            targetEvent: ev,
            clickOutsideToClose:true
        }).then(function(answer) {
            $scope.status = 'You said the information was "' + answer + '".';
        }, function() {
            $scope.status = 'You cancelled the dialog.';
        });
    };
});

function DialogController($scope, $mdDialog) {
    $scope.hide = function() {
        $mdDialog.hide();
    };
    $scope.cancel = function() {
            $mdDialog.cancel();
    };
    $scope.answer = function(answer) {
        $mdDialog.hide(answer);
    };
}

This is what I have in my HTML page:

<a ng-click="openDetailDialog()">Show details</a>
<script type="text/javascript">
    function openDetailDialog(id) {
        var id = getValue(id, 'id');
        showAdvanced($event,'${readDetailURL}&id=' + id + '/');
    }
</script>

The issue I'm facing is that when I nest the showAdvanced() function within another function, it doesn't work. However, when I directly call the function in the ng-click, it works.

For example, this directly calling the function works:

<a ng-click="showAdvanced($event,'http:myurl/test/id');">Show details</a>

Can someone explain why?

Answer №1

One thing to note is that you cannot link or connect something that does not exist on the $scope or within the controller itself.

<a ng-click="openDetailDialog()">Click here for more information</a>

This statement is incorrect.

Another important point is that accessing variables attached to the scope from plain javascript is not possible, as two-way data binding only interacts with HTML. Angular operates with an encapsulated scope.

Answer №2

The showAdvanced() function is actually a part of the $scope element. When you use it in your HTML like this:

<a ng-click="showAdvanced()">text</a>

AngularJS will covert that (behind the scenes) to $scope.showAdvanced()

If you need to call it from JavaScript, you can change your function call to

`$scope.showAdvanced()`

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

Calling a function upon a checkbox event change and passing an object to it

I am attempting to implement a checkbox change so that when it is clicked, a value is added to my object. I tried using an onclick event since jQuery wasn't working for me. Here is the code snippet: The object is named Contact() and contains 'ad ...

Updating the opacity of the alphaMap in THREE.JS R76 does not cause the desired change

I am working on a tunnel project that involves a rotating texture and alpha map. My goal is to adjust the opacity of the alpha map using tweening effects. Initially, I set the opacity to 0 and then try to increase it gradually. However, the live view does ...

Update the $scope variables with new data fetched from a service

How should I properly update the data retrieved from my service? I am fetching a test array from my dataService and want it to automatically reflect in my view when I call the save() method. Even though I have included the line that is supposed to update m ...

The input unexpectedly reached its limit, causing a jquery error

Encountering an error that says: Uncaught SyntaxError: Unexpected end of input on line 1. Check out the code below: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html x ...

Creating a dropdown menu for an extensive list of 100 menu items: a step-by-step guide

In my React JS front-end project, I have implemented a drop-down menu using Material-UI. Currently, the menu items are hardcoded which works fine for a small number of items. However, this approach becomes cumbersome when dealing with a larger number of ...

Uncovering the source of glitchy Angular Animations - could it be caused by CSS, code, or ng-directives? Plus, a bonus XKCD comic for some light-hearted humor

Just finished creating an XKCD app for a MEAN stack class I'm enrolled in, and I'm almost done with it. However, there's this annoying visual bug that's bothering me, especially with the angular animations. Here is the link to my deploy ...

What is the best method to remove the content of a div without using innerHTML = "";?

My dilemma lies in a div that is populated with dynamically created DOM elements via JS. As I strive for the div to refresh each time the JS function runs again, various sources have advised against utilizing document.getElementById('elName').in ...

Navigate Formik Fields on a Map

Material UI text-fields are being used and validated with Formik. I am looking for a way to map items to avoid repetitive typing, but encountering difficulties in doing so. return ( <div> <Formik initialValues={{ email: '&a ...

Tips for showcasing a string value across various lines within a paragraph using the <br> tag for line breaks

I'm struggling to show a string in a paragraph that includes tags to create new lines. Unfortunately, all I see is the br tags instead of the desired line breaks. Here is my TypeScript method. viewEmailMessage(messageId: number): void { c ...

How can you refresh a single element within an array using Angular.js?

System Background: The application is developed using Angular for the front end with routing capabilities, and Node.js, Express, MongoDB, and Mongoose for the back end. Within a controller, there is an array named $scope.array=[]; that is populated throug ...

Exploring a personalized approach to searching in DataTables

I am facing a dilemma with implementing a custom search in a DataTables table due to my limited experience with JavaScript. The function I have only triggers on startup and not when typing in the search box. If you're interested, you can find my orig ...

The mobile navigation in HTML has a slight issue with the ::after pseudo-element, specifically within the

As I prepare to launch my website, I have made adjustments to the mobile layout by moving the navigation links to a navigation drawer. The template I am using included JavaScript scripts to handle this navigation change. However, I encountered an issue whe ...

How can I prevent my JSON object from serializing .NET nulls as "null" for object members?

I am currently utilizing WebMethods to retrieve an array of a custom class. When this array is returned from a Jquery .ajax call, it gets serialized into a JSON object that can be utilized with Javascript in my ASP.NET application. The issue I am facing is ...

How to implement a self-invoking function in React JS like you would in regular JavaScript?

Is it possible to invoke the function good without triggering it from an event? I want it to run as soon as the page loads, similar to a self-invoking JavaScript function. Check out this example import React from 'react'; class App extends Reac ...

Switching from using jQuery's $.ajax method to Angular's $http service

I have been working on a jQuery code snippet that works seamlessly across different origins: jQuery.ajax({ url: "http://example.appspot.com/rest/app", type: "POST", data: JSON.stringify({"foo":"bar"}), dataType: "json", contentType: "a ...

Interrupted Exception in Azure Mobile Services EasyApi for Java

I have implemented a new simple API named "test" in my MobileService. Currently, I am attempting to make a request from Android to fill my passed object: Exists result = mClient.invokeApi("test","ID" ,Exists.class).get(); The structure of my 'Exi ...

Using a div in React to create a vertical gap between two React elements

I am working with two React Components in my project - the Right Column and the Left Column. I am trying to create space between them using a div tag. Currently, my setup in the App.js file looks like this: import React from 'react'; import LeftC ...

Finding the minimum value in a list and the maximum value in JavaScript

My current JavaScript list consists of dollar coin values: let x = [1.0, 2.5, 5.0, 20.0, 50.0, 100.0, 500.0, 2000.0, 5000.0] My challenge is finding an equation in JavaScript that will allow me to use the smallest number of coins to reach the desired max ...

Gather information on a webpage

I am attempting to extract a table from the following page "https://www.hkex.com.hk/Mutual-Market/Stock-Connect/Statistics/Historical-Monthly?sc_lang=en#select1=0&select2=0". After using the inspect/network function in Chrome, it appears that the data ...

Transferring Object Information from AJAX to PHP

When attempting to send data to a PHP file for database storage, I am not receiving any response. If a checkbox is checked, the [obj][idCheckbox] value is set to 1; otherwise, it is set to 0. This is the file responsible for sending the data: var i=0; v ...