Exploring ways to access properties from a parent controller in AngularJS when working with a modal controller - determining

My journey to learn AngularJS is a continuous process, and I am eager to understand the reasons behind choosing one approach over another in specific scenarios. Is it a matter of personal preference or more than that? Let's explore some examples.

In both scenarios described below, when a user clicks the OK button, the create() function from the parent controller is triggered by the child controller.

RESOLVE STYLE

CreateController

...

var vm = this;

vm.create = create;

function create() {
    console.log('Created!');
}

vm.openCreateModal = function() {
    vm.modalInstance = $uibModal.open({
        ...
        resolve: {
            create: function() {
                return create;
            },
            // Additional resolves if needed
        }
    });
}

...

CreateModalController

...

vm.ok = function() {
    create();
    $uibModalInstance.close('ok');
};

...

SCOPE STYLE

CreateController

...

var vm = this;

vm.create = create;

function create() {
    console.log('Created!');
}

vm.openCreateModal = function() {
    vm.modalInstance = $uibModal.open({
        ...
        scope: $scope,
        resolve: {
        }
    });
}

...

CreateModalController

...

vm.ok = function() {
    $scope.$parent.vm.create();
    $uibModalInstance.close('ok');
};

...

Update

The reason for my inquiry stems from the debate around accessing or injecting objects from a parent/root/container service/controller into another controller/service being considered a "bad practice" in some languages/frameworks I have encountered before.

Answer №1

The concept behind the resolve function is to execute it before initializing the remaining part of your code. Typically, resolve is used in the routing section like the example below:

$routeProvider
        .when('/', {
            templateUrl: "views/view.html",
            caseInsensitiveMatch: true,
            resolve: {
                load: function() {
                    localStorage['Location'] = "/View";
                }
            }
        })

In the given scenario, the load function will be executed by resolve before my controller gets initialized. Conversely, scope is utilized for direct binding within a controller or directive. It is recommended to use scope when calling functions and linking values across controllers and directives.

Additionally, expanding on the comments provided, if the resolve encounters an issue, it will reject the modal and prevent the window from opening.

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

What is the best way to open up a parent CSS accordion when the child accordion's border is covering the parent's border?

Exploring Options and Background https://example.com/jsfiddle I have been experimenting with creating an expandable/collapsable accordion for displaying restaurant food choices, envisioning a digital menu akin to Just-Eat or Hungry House. My attempt inv ...

Determine whether the color is a string ('white' === color? // true, 'bright white gold' === color? // false)

I am facing an issue with multiple color strings retrieved from the database. Each color string needs to be converted to lowercase and then passed as inline styles: const colorPickerItem = color => ( <View style={{backgroundColor: color.toLowerC ...

Retrieving information from jQuery object using jQuery

I am utilizing ajax to retrieve information from the database. Once I have retrieved the information from the table, I am using json_encode to format the data into JSON. Then, I am utilizing parseJSON to display the data in JavaScript. After receiving the ...

Unable to process form submission using Ajax in ASP.NET MVC

I'm having trouble with submitting a form using ajax and opening a modal dialog after the ajax function is successful. Whenever I click the submit button, the process doesn't complete. Where could the issue be, in the ajax method or somewhere el ...

Tips for dynamically assigning values to scope variables in AngularJS

My ng-model looks like this: <tr ng-repeat="user in users"> <input type="text" ng-model="code[user.id]"/> When I set $scope.code = {0: 'value'};, it works fine. However, if I try to pass a dynamic value like: var index = 0; $scope ...

JavaScript capable of storing vast quantities of data

Currently, I am receiving file chunks in byte format from my server and combining them into one variable on my frontend for downloading later. Unfortunately, I am unable to modify the server setup which sends files sliced into chunks. The issue arises whe ...

Encounter an issue while using CreateAsyncThunk due to a 400 Bad Request

I have encountered an issue with my asynchronous thunk. Even when the status code is 400, the request result remains fulfilled. How can I handle a 400 error using createAsyncThunk and the fetch API? This is the action code: import { createSlice, creat ...

Is it possible to input a parameter into a resource without modifying the route?

Essentially, I am attempting to pass a parameter from my Angular app to my NodeJS service. The GET request in question looks like this: resource: $resource(nodeRoute + '/test'. {}, { query: { method: 'GET', ...

Unable to Retrieve Modified Content with $().text();

In the process of developing an app, I am encountering a challenge where I need to transfer user input to another element after processing it. However, I am facing an issue with accessing the updated value of the <textarea> using .text(), as it only ...

Passing the response from an AJAX request to JavaScript

When I call ajax to retrieve a value from an asp page and return it to the calling javascript, the code looks like this: function fetchNameFromSession() { xmlhttp = GetXmlHttpObject(); if (xmlhttp == null) { alert("Your browser does n ...

How to Add Functionality to Angular Apps Without Defining a Route

One unique aspect of my website is the navigation bar. It appears on some pages but not others, so I've created a controller specifically for it. Here's how the navigation bar markup looks: <html ng-app="myApp"> <head> <title& ...

Executing a server-side Java function from client-side JavaScript or jQuery on a JSP page

My JSP file has a dropdown list where I can select different entity kinds. Upon selecting an entity kind, I want to populate another dropdown list with the field names associated with that entity kind. This requires calling a JavaScript function when chang ...

Do these two JavaScript statements behave the same under the principles of functional programming in a React environment?

Is there a rule in functional programming that states these two approaches are equivalent? When working on a React application, I initially passed a function as an attribute using the second version where the first parameter is also passed. Out of curiosi ...

Fragment errors detected in the Menu Component

I am facing an issue with my code where I am getting an error in the console saying that the Component cannot receive fragments as children. How can I remove the fragments while retaining the logic? Every time I attempt to remove the fragments, I encounter ...

Could not find reference to Google (error occurred following ajax request)

I encountered an error message when attempting to use the Google Map after making an ajax call. ReferenceError: google is not defined The issue arises when I include the link "<script type="text/javascript" src="http://maps.google.com/maps/api/js?sen ...

delivering json replies with abundant data

I am facing an issue where the data sent to my view does not correspond to the data generated by the query. Only a single data entry appears. Here is the function in question: function lokasi_ajax() { var kode_lokasi = $('#kode_lokasi').val() ...

navigating the matrix of arrays in ReactJS / JavaScript

I have a snippet of code available at this link. Currently, I am working with an array of arrays containing data. const data = [ [ { city: "Phnom Penh", country: "KH" }, { city: "T ...

Preserving scroll location in Laravel when posting updates

I am facing an issue with the commenting system in my Laravel application. Whenever a user submits a comment, the page reloads and takes the user back to the top of the page. I would like the page to return the user to the same position where the original ...

Scrolling horizontally in md-list

I have a list of items where each item can be of varying lengths horizontally: https://i.sstatic.net/ITIQd.png The issue is that long items are getting cut off on the right side. Here's the code snippet I am currently using: <md-list-item ng-repea ...

Tips for generating nested elements in JSON and Java, alongside accessing the subitem values in JavaScript

By implementing this code, I was able to create the following structure int n=3; String json []= new String [n]; try { JSONArray js = new JSONArray(); ArrayList<String> ciudades; ciudades = ...