Unique: "Best Practices for Setting Angular.js Controller Data Directly in the Code"

In this scenario, I need to initialize the data from an inline script, even though I know how to achieve this using a promise on an http request.

Currently, the controller is already defined in the header js:

var testModule = angular.module('myTestModule', []);
testModule.controller('testCtrl', function ($scope) {
    $scope.data = [];
});

Below is the HTML that loads. Let's assume that the script part takes a significant amount of time to complete:

<div ng-app="myTestModule" ng-controller="testCtrl">
...
</div>
<script type="text/javascript">
    setInitialData(['boo', 'far']);
</script>

If the inline script were loaded BEFORE the div with ng-app, everything would work fine. However, in this case, it might load after the controller has been instantiated. I want to avoid making an extra http request, but at the same time, I see the convenience of using a promise with an angular service.

Does anyone have suggestions on how to design the function setInitialData so that it can apply the data to the controller/scope?

Answer №1

If you want to access the scope of any DOM element in AngularJS, you can utilize the angular.element(...).scope() method. A helpful tip is to use angular.element($0).scope() in the devtools JS console to grab the scope of the currently selected element in the Elements tab.

Once you have the scope reference, you can make necessary changes to it. Remember to invoke $apply() to notify AngularJS about the modification.

For instance:

<div ng-app="myTestModule" ng-controller="testCtrl" id="testCtrl">
...
</div>
<script type="text/javascript">
    function setScopeValue(selector, scopeProp, value) {
        angular.element(selector).scope().$apply(function ($scope) {
            $scope[scopeProp] = value;
        });
    }

    function setInitialData(data) {
        setScopeValue('#testCtrl', 'data', data);
    }

    setInitialData(['boo', 'far']);
</script>

Please note that the setScopeValue() function provided only supports a single level of property access and does not allow for nested properties. If you require setting nested properties, consider using $parse() to generate a setter function that can be called with the $scope and the value to be assigned.

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

Unable to retrieve ng-model value in AngularJS controller

I am facing an issue while trying to access the ng-model name viewProfileCtrl.monthsForm.institution in my Controller. <select class="perf-select" ng-model="viewProfileCtrl.monthsForm.institution" ng-options="inst.institution ...

Locating the elusive sequence number within a document

Greetings, I am currently trying to locate a missing number within an xml file but seem to be encountering some challenges. Any suggestions or ideas would be greatly appreciated. Example The file contains an <a> tag with various ids such as page-1, ...

Interface key error caused by the TypeScript template literal

Version 4.4.3 of Typescript Demo Playground Example -- interface IDocument { [added_: `added_${string}`]: number[] | undefined; } const id = 'id'; const document: IDocument = { [`added_${id}`]: [1970] } My Attempts: I made sure that id in ...

What is the way to modify the contents of a div using ajax?

I have blade files in both list and image formats. There are two span buttons here, and I would like to display a list in different formats when each button is clicked. How should I go about writing the code for this? <span id="penpal-image-view" ...

Dynamic Data Causes Highcharts Date Formatting to Adapt

I wanted to create a line graph using Highcharts with the Date Format on x-axis set to "%b %e". For example, I expected 06/27/2014 to be displayed as Jun 17. Despite setting the date-format correctly, Highcharts seems to automatically change it when rende ...

JavaScript cannot determine the length of an array of objects

I'm encountering an issue with an array of objects named tagTagfilter. When I log it in the browser, it doesn't immediately show the correct length value inside. tagTagFilter: TagFilter = { filterName: 'Tag', tags: [] ...

Upcoming examination on SEO using React testing library

Currently, I am in the process of testing out my SEO component which has the following structure: export const Seo: React.FC<Props> = ({ seo, title, excerpt, heroImage }) => { const description = seo?.description || excerpt const pageTitle = s ...

Why is only the peak of the wave visible? I am eager to showcase the full extent of its beauty

Having an issue with the appearance of a superposed wave using threejs. When displayed, the wave made from plane material only shows the upper half, but when turned upside down using mouse dragging, it appears correctly. // Turn the wave plane upside down ...

Script for converting Fixed Positioned Elements to Static

I am frequently finding that elements on web pages are causing disruptions due to their fixed positioning. I am exploring ways to disable the position: fixed CSS rules on any website I visit. To address this issue, I have developed a userscript specifical ...

AngularJS and jQuery offer a convenient way to restrict the selection of future dates in a datepicker

Hello, I am having trouble disabling future dates on my datepicker. I have tried multiple methods but haven't been successful. Can you please point out where I might be going wrong? <div class="input-group date"> <input type="text" clas ...

How can you effectively use a table filter extension to sort through dropdown values?

Is there a way to update the dropdown values based on new data after applying the first filter? For example, only displaying $0 in the second dropdown menu? Essentially, I want to filter the values in a table and then have the dropdown options reflect the ...

What is the process of displaying JSON headers using JavaScript?

Although it may seem like a simple question, I am new to JSON. Can someone explain how to display a heading in the console? This is the code I have: var jsonstr = '{"profile":{"name" : "raj","age":"35&qu ...

When working with an array of objects in Vue.js, what is the optimal approach: replacing the entire array or modifying individual values?

I am currently utilizing Vue and Vuex to dynamically generate components from an array retrieved from SQLite using the library better-sqlite3. let table=[ { id:1, column_1:'data', column_2:'data', column_3:{'1&apo ...

What steps can I take to improve my routing structure in nodejs and express?

My current WebAPI code is pretty modular, but I want to make it even more so. Right now, all the routes are in my server.js file and I would like to separate them into individual controllers. Any suggestions on how to achieve that? Here's an example: ...

Tips on harnessing the power of AngularJS $scope

In need of assistance! I have a paragraph and a counter that I want to update whenever the user clicks on the paragraph, all using AngularJS. Below is the code snippet I've come up with: <!DOCTYPE html> <html> <head> <script src= ...

JavaScript encounters a parsing error when dealing with an async function

Ever since I developed a node.js web application, I've been utilizing MSSQL for the database. To streamline SQL functions, I crafted functions (sql.js) to handle all the necessary queries. Furthermore, I set up async function handlers (controllers.js) ...

There seems to be an issue with node.js - headers cannot be set after they have already been sent to

As I work on developing my blog, I've encountered an issue with rendering different paths using the router parameter. Each time I attempt to display another route, an error surfaces. Unfortunately, I'm unable to provide more details at this momen ...

Troubleshoot: Issue with Navbar Dropdown Expansion on Bootstrap Sass 3.3.6 with JavaScript

Beginner: Bootstrap Sass 3.3.6 - Incorporating Javascript - Issue with Navbar Dropdown Not Expanding application.html.erb Head: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> ...

Exclusive Modal Pop-Up for First-Time Visitors - Utilizing Bootstrap, PHP, and JavaScript

Seeking assistance from the community as I have exhausted my online research efforts. I am currently working on implementing a welcome bootstrap modal in a php environment. Despite being new to php and js, I have managed to make it pop up only once using ...

The interaction between Vue components causing changes in each other's data

Currently, I am working on a project using vue/nuxt. In order to dynamically load data from a JSON file during compilation, I am utilizing nuxt and webpack (Dynamically get image paths in folder with Nuxt). The structure of my JSON file is as follows: { ...