Sending a javascript variable to an angularjs scope

Currently, I am utilizing Flask to render an HTML template and wish to transfer the variable add_html_data, which is passed via Flask's render_template, to the scope of an AngularJS controller.

I have attempted the following:

<body>
    <div ng-controller="layoutController" ng-init="entries= {{ add_html_metadata|tojson }}"/>
</body>

In this scenario, the {{}} denotes Flask variables (I modified AngularJS binding syntax to {[{}]}).

Additionally, I tried creating an intermediate JavaScript variable:

<script type="text/javascript">var entries = {{ add_html_metadata|tojson }}</script>

Nevertheless, I am still unable to discern how to link it to the controllers scope.

Appreciate any help provided.

Answer №1

To begin, consider implementing an init() function within your controller:

app.controller('layoutController', function($scope) {
    $scope.init = function(html_metadata) {
        $scope.html_metadata = html_metadata;
    }
});

Subsequently, in your template, you can execute this function with the provided data:

<body>
    <div ng-controller="layoutController" ng-init="init({{ add_html_metadata|tojson }})"/>
</body>

Answer №2

Perhaps @Miguel's suggestion could be effective, however, my approach would involve creating a RESTful request to fetch the JSON data labeled as add_html_metadata. Utilizing a $http call to assign this data to the controller's scope is considered the AngularJS methodology. The implementation could look something like the following:

@app.route("/retrieve_html_metadata", methods=["GET"])
def fetch_html_metadata():
   # perform necessary actions here
   return jsonify(html_metadata)

Correspondingly, within the AngularJS controller:

myApp.controller('layoutController', ['$scope', function($scope) {

  $http({method: 'GET', url: '/retrieve_html_metadata'}).
    success(function(data, status, headers, config) {
      $scope.html_metadata = data;
   }); 
}]);

Answer №3

My knowledge of flask is limited, but I suggest utilizing ng-include

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 use Immer to update Zustand state when incorporating objects that are added through a controlled form using React-Hook-

Having some trouble with integrating Zustand and Immer using React-Hook-Form. My goal is to capture a series of values from a form, store them in a list, and allow for the addition of new objects to that list. In this scenario, the user inputs data for a ...

Are your JavaScript scripts causing conflicts?

My bootstrap Carousel was working perfectly fine until I added a script to modify the navigation bars. The original script for the Carousel looked like this: <script> !function ($) { $(function() { $('#myCar ...

Remove a div element with Javascript when a button is clicked

I am working on a project where I need to dynamically add and remove divs from a webpage. These divs contain inner divs, and while the functionality to add new divs is working fine for me, I'm facing some issues with removing them. The code snippet b ...

Using JavaScript and jQuery to compare two JSON objects, then storing the result in a separate object

I am currently working on an API call that provides an updated JSON object, as well as a static JSON object file. My goal is to compare a specific value in the objects for teams with the same name. For example, if Team John had 22 members in the old file ...

How to trigger a file download instead of opening it in a new tab when clicking on a txt or png file in AngularJS

After retrieving my file URL from the backend API, I am trying to enable downloading when the user clicks a button. Currently, the download function works smoothly for Excel files (`.xlsx`), but for text (`.txt`) files or images (`.jpeg`, `.png`), it only ...

Update the image source every few seconds

I am attempting to show the same image in both gif (animated) and jpeg formats. I am updating the src every few seconds. After checking in the developer tools, it seems that the src has been modified, but the gif does not appear to be animating. setInter ...

Ways to implement Formik to output a boolean value?

Currently, I am facing an issue retrieving a value from Formik. While it works perfectly fine with a Textfield component, I am unable to fetch the value of my switcher (which is a boolean). The setup for my file and switcher looks like this: <div clas ...

Adjusting the minimum value on a textfield with JQuery Validate plugin in real-time

I am attempting to dynamically update the minimum value on one field based on input from other fields. Here is a brief overview of my code: $("#new_project").on("click", function() { switch($('input:radio[name=quality-level]:checked').val() ...

The authentication protocol, Next Auth, consistently provides a 200 status response for the signIn function

I ran into a challenge while building my custom login page using Next Auth. The issue arises when I try to handle incorrect login data. If the login credentials are correct, I am able to successfully send JWT and redirect to /dashboard. However, when the l ...

Changing the event handler of a jQueryUI accordion dynamically from "click" to "mouseover" as needed

I am facing a scenario where I need to drag an item from a list and drop it into a target within an accordion. The challenge is that the target may be in a panel that is not currently open. To address this issue, I am looking to dynamically switch the acc ...

Setting a completion flag using a factory in AngularJS

I'm struggling to create a factory that can set a completion flag for a value within an object. The object in question looks like this: {"key1":"value1", "key2":"value2", "key3":"value3"} My goal is to retrieve and operate on the value associated wi ...

Vue.js variable routes present an issue where the Favicon fails to appear

I've successfully set my favicon in the index.html file for my Vue webpack SPA. It displays properly when I visit the main site or any standard route, but it fails to show up when I navigate to a dynamic route (path: "/traduzione/:translation"). I&ap ...

The error message "ng: command not found" popped up despite successfully installing the latest @angular/cli using npm linking

Here is the information about my current setup: Node version: v10.15.3 NPM version: 6.4.1 I attempted to run the following command: Command: npm i -g angular/cli An error occurred while executing: npm ERR! /usr/local/bin/git ls-remote -h -t ssh:// ...

Creating a read-only DIV using Angular - a step-by-step guide

Is there a simple way to make all clickable elements inside a div read only? For example, in the provided HTML code, these divs act like buttons and I want to disable them from being clicked. Any tips or shortcuts to achieve this? Thank you. #html < ...

What is the best way to update the innerHTML of a date input to reflect the current value entered by the user?

Currently, my task involves extracting data from a table by obtaining the innerHTML of each row. The table contains date inputs that can be manually adjusted or generated automatically. However, the innerHTML does not update accordingly. Thus, when exporti ...

The functionality of window.location.href seems to be malfunctioning on mobile devices within an ionic application

Attempting to open a view with a function call from the UI side <ion-option-button class="button-light icon ion-chatbubble" ng-click="openView('username')"></ion-option-button> The controller code for this action is as follows: $sc ...

What is the secret to creating a button that can sort text and another button that flips the word density in my content?

I'm not a fan of having something like this because it's displeasing to the eye: https://i.stack.imgur.com/3F4sp.jpg Instead, I prefer my word density to be more organized and structured. How can I achieve this? Sort by highest word density fi ...

Transform Vue.js into static HTML output

Is there a way to convert a Vue.js component into static html without the need for javascript? I am specifically interested in retaining styles. I am searching for a library where I can execute code similar to this: SomeNestedComponent.vue <template> ...

Issue: The error message "undefined variable 'angular'" appears when attempting to access offline files stored on a network drive

I have successfully developed offline forms using angular js v1.6.4, angular-ui-bootstrap, and angular-ui-router without the need for server hosting. When the package is saved on local storage, it functions perfectly on both IE and Chrome browsers. Howeve ...

A guide on iterating through an array in vue.js and appending a new attribute to each object

To incorporate a new property or array item into an existing virtual DOM element in Vue.js, the $set function must be utilized. Attempting to do so directly can cause issues: For objects: this.myObject.newProperty = "value"; For arrays: ...