Using Angular JS, the JSON method is invoked from a location external to the controller

How can I call an inner method from outside a controller in AngularJS?

var app;
(function (){
app = angular.module("gallery", []);

app.controller("galleryController", ['$scope','$http', function($scope, $http){
    var gallery = this;
    gallery.data = [];

    gallery.getJson = function(){
        $http.get('/urltojson/main-hero.json').success(function(data){
            gallery.data = data;
        });
    }

    this.getJson();
}]);  })();

Is it possible to call the getJson method from outside the controller?

Answer №1

To access the scope of an element within a specific controller in Angular, utilize the angular.element method.

For instance:

<div ng-controller="appController"><p id="example"></p></div>

You can then execute:

var newScope = angular.element( document.querySelector( '#example' ) ).scope();
newScope.getData();

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

Decoding JSON to extract nested dictionaries in Python

My json file contains an object with a dictionary nested within it: { "__class__": "monster", "name": "Mugger", "level": 1, "hpTotal": 20, "attacks": ["Sword", "Knife"], "stats": { "AC": 12, "STR": 11, "DEX": 12, ...

Pass data to child component in react

I have a parameterized component that can take a value of true or false, and I'm using console.log to verify it. console.log(isContract); //can be true or false Now, I need to pass this value through a form to render another component. This is the p ...

Parsing JSON with NewtonSoft JsonConvert

I encountered this error while trying to deserialize JSON text: Unexpected character encountered while parsing value: {. Path '[0]', line 1, position 3. The JSON Text was validated on JSONLint.com and here is the JSON text: [ [ {"t ...

Access control using Vue.js Cookies

Within my current project, we have both superusers and staff members. The specific task of deleting users is reserved for the superuser role only. This leads me to question whether it is plausible to delete a user by utilizing cookies? ...

The conundrum of posting with Mandrill in Swift

My current task involves sending an email using the Mandrill API. I came across some Swift code here that demonstrates a JSON HTTP POST method: func createRequest(myUrl : String, type : String, params : NSDictionary?, completion : (AnyObject?, NSError?)-& ...

Implement a function to trigger and refresh components in various Vuejs2 instances simultaneously

I currently have index.html with two Vue instances in different files: <!DOCTYPE html> <html lang="en"> <body> <div id="appOne"> </div> <div id="appTwo"> </div> </body> </html ...

Why isn't my JavaScript variable visible in the HTML code?

I am currently facing an issue with my Angular app where I am trying to display a JavaScript variable in HTML. The variable successfully shows up in an older part of my application, but it fails to do so in the new section. Below is the functional code sn ...

Discover the ultimate solution to disable JSHint error in the amazing Webstorm

I am encountering an error with my test files. The error message states: I see an expression instead of an assignment or function call. This error is being generated by the Chai library asserts. Is there a way to disable this warning in Webstorm? It high ...

What is the best way to access a cached value?

I am currently utilizing the node-cache-manager library to manage caching in my Node.js application. After successfully adding an item to the cache using the following code: import cacheManager from 'cache-manager'; const memoryCache = cacheMan ...

Typescript: Verifying the type of an interface

In my code, I have a function called getUniqueId that can handle two different types of interfaces: ReadOnlyInfo and EditInfo. Depending on the type passed to this function, it will return a uniqueId from either interface: interface ReadOnlyInfo { item ...

What is the best way to import JSON functionality into Javascript specifically for use with Internet Explorer

I am facing an issue with loading JSON feature in JavaScript for IE8 while in compatibility mode. After receiving advice, I decided to utilize douglascrockford/JSON-js to enable JSON support on outdated browsers. To tackle this problem, I created a new f ...

How can the formatResult and formatItem options enhance the functionality of JQuery Autocomplete?

I'm a bit puzzled here - can someone explain what the formatResult and formatItem functions do in the JQuery Autocomplete plugin? I have a function that returns a comma-separated string from Django, but I'm having trouble getting my autocomplete ...

Definitely typed AngularJS in Visual Studio 2015 is a powerful combination for

I've been working on my first AngularJS project using Visual Studio 2015 and everything was running smoothly until I decided to switch to Typescript. After installing the DefinitelyTyped projects, I started getting numerous error messages. Here' ...

Cannot utilize structuredClone() on the value of the reference variable

I am looking to implement the structuredClone() function in my Vue application. I want to use it for creating a deep clone without resorting to methods like stringify and parse or third-party libraries. In my setup function, the following code works fine: ...

Default value for the href property in NextJS Link is provided

Is there a default href value for Next/Link that can be used, similar to the way it is done in plain HTML like this: <a href='#' ></a> I attempted to do this with Link, but it resulted in the page reloading. Leaving it empty caused a ...

Utilizing a Spring Kafka listener to consume JSON data and automatically determine the corresponding domain object

I have a project where I need to process various types of JSON messages that will be published. Unfortunately, I cannot modify the publisher's code to include any headers. However, I am interested in utilizing @KafkaHandler to manage these different J ...

Error: The function "JSON_BUILD_OBJECT" cannot be located

When conducting tests, I am utilizing the h2 database. The settings for my test h2 database are as follows: private static final String JDBC_URL = "jdbc:h2:mem:test;MODE=PostgreSQL;DB_CLOSE_DELAY=-1"; Connection connection = DriverManager.getConn ...

Transforming iframe programming into jquery scripting

Currently, I have implemented an Iframe loading the contents within every 5 seconds. It works well, however, there is a consistent blinking effect each time it loads which can be quite bothersome. I am looking to replace the iframe with a scrolling div so ...

Determine the viral coefficient based on the sharing platform being used, whether it is Facebook or Twitter

Traditionally, the viral coefficient is measured through email addresses. For example, if a current user [email protected] invites 10 people via email, you can track how many signed up and calculate the viral coefficient based on that. But what if th ...

How can you determine the number of elements that match in two arrays?

As a coding newbie, I'm looking to create a JavaScript function that compares two arrays and assigns a score based on the number of matching elements. However, when I attempt to run it in Chrome's console, I receive an error message stating that ...