Retrieving a universal variable within AngularJS

Is there a way to initialize an Angular model using a JSON object that is embedded within an HTML page? Take this as an example:

<html>
  <body>
    <script type="text/javascript" charset="utf-8">
      var tags = [{"name": "some json"}];
    </script>
    <ul>
      <li ng-repeat="tag in tags">{{tag.name}}</li>
    </ul>
  </body>
</html>

The tags field doesn't resolve because it's being looked up in the $scope. I attempted to access the tags field in my controller like so:

function TagList($scope, $rootScope) {
  $scope.tags = $rootScope.tags;
}

However, this method isn't successful.

It only works if I directly include the TagList within the HTML page and render the JSON directly into this function.

Is there a way to access the tags field in a separate JavaScript file within an Angular controller?

Answer №1

There are a couple of methods you can use:

  1. To begin with, create your tags array in a separate script block, which will bind your tags variable to the window object. Then inject $window into your controller to access these window-bound variables.
  2. Alternatively, declare your tags array within the ng-init directive.

Here are both solutions demonstrated:

HTML:

<body>

  <script type="text/javascript" charset="utf-8">
    var tags = [{"name": "some json"}];
  </script>

  <div ng-controller="AppController">
    tags: {{tags | json}}
    <ul>
      <li ng-repeat="tag in tags">{{tag.name}}</li>
    </ul>
  </div>  

  <div>
    <ul ng-init="tags = [{name: 'some json'}]">
      <li ng-repeat="tag in tags">{{tag.name}}</li>
    </ul>
  </div>

</body>

JS:

app.controller('AppController',
  [
    '$scope',
    '$window',
    function($scope, $window) {
      $scope.tags = $window.tags;
    }
  ]
);

Plnkr

I recommend avoiding cluttering the window object with unnecessary variables.

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

Error: Attempting to convert a circular structure to JSON in Node.js

Encountered an error when attempting to retrieve my API using Postman: TypeError: Converting circular structure to JSON --> starting at object with constructor 'NativeTopology' | property 's' -> object with constructo ...

Navigating an Array in Typescript

Angular is linked to node.js, which interacts with mongodb to fetch data successfully. However, I am now faced with the challenge of mapping variables in my typescript component to the backend node.js. When viewing the data structure in the browser consol ...

Utilizing Flutter and Dart to efficiently convert JSON time series data into a map structure containing key-value pairs

Encountered a message regarding "anonymous closure" in the TimeSeriesAdjusted.fromJson method, indicating a subtype error that I'm having trouble identifying. [VERBOSE-2:ui_dart_state.cc(199)] Unhandled Exception: type 'Null' is not a subtyp ...

Using the base tag in Angular HTML5 mode can cause script links to break

Issue Following the configuration of a base tag to enable Angular 1.x in HTML5 mode, encountering an error where the browser (Chrome) sends requests to an incorrect path for scripts when directly accessing the app via localhost:3000/resource/id. Specific ...

Using a data() object in Vue to fill out form fields efficiently

My data retrieval process from mongodb involves obtaining the data and transferring it to the client side using the following approach: error_reporting(E_ALL); ini_set('display_errors', '1'); require '../vendor/autoload.php'; ...

Using AngularJS to dynamically populate select options from an array of objects within an object

I am trying to display my data in a list format like this: <option value="4351">Atlanta</option> Here is the content of my object. $scope.cityList = { 4351:{name:"Atlanta", short="atlanta"}, 7355:{name:"Baltimore", short="baltimore"} ...

Testing an ExpressJS route and their corresponding controller individually: a step-by-step guide

I have set up an Express route in my application using the following code snippet (where app represents my Express app): module.exports = function(app) { var controller = require('../../app/controllers/experiment-schema'); app.route('/a ...

"Dynamically moving" background on canvas

Struggling to animate a dynamic "background" for my canvas project using raphaelJS. Here's the code snippet I'm working with: function bg(){ h = 0; var terra = paper.rect(0, 500 + h, 900, 100); terra.attr({'fill': '# ...

Issue with Datatables FixedColumns plugin in IE8/7 and Firefox

I am encountering issues with the FixedColumn plugin on IE8, IE7, and Firefox. All of them are causing my table to malfunction, displaying the following error: Error: Invalid argument. Line: 566 Char: 3 Code: 0 URI: ./resources/javascript/dataTable/Fixed ...

The successful JSON response in an Ajax request is not functioning as expected

I've set up a data table that allows users to add rows by clicking the "plus" button. This triggers an ajax request to a URL with the rowId as a parameter (which corresponds to the specific row where the button was clicked). I expect to receive a JSON ...

Serve JSON response as text/json in Scala Play 2.1

I'm using Play! 2.2 with Scala and I'm attempting to return a JSON response. The current code serves the response as application/json, but I need it to be served as text/json. While researching, I came across some documentation on . However, the ...

The progress bar for uploading a file is causing issues with the redirect function in the

I am currently facing an issue with my file submission form and progress bar in JavaScript. The progress bar is interfering with the controller, preventing it from redirecting back home with the link. I have tried removing window.location.href="/"; but thi ...

Top approach for triggering and re-triggering AJAX using php

I'm in the process of deciphering instructions from my developer. Our approach may not be entirely correct, so I want to ensure that we are on the right track. This is our objective: On a webpage, there exists a button. When this button is clicked, I ...

Implementing Express 4: The Correct Way to Serve Routes from External Files

Something about my Express 4 application is causing me frustration. Here's the configuration: routes/profile.js var express = require('express'); var router = express.Router(); router.get('/profile', function(req, res) { res.s ...

What is the best way to incorporate CDN into my webpack build process?

I have developed a module with the following code: export default () => console.log('hello my_module~!') The configuration in the webpack.config.js file looks like this: module.exports = { // ... output: { // ... library: 'he ...

Traverse dictionaries in jq shell

I have a JSON object with various image details { "images" : [ { "size" : "29x29", "idiom" : "iphone", "filename" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="357c565a5b18665854595975074d1b455b52"& ...

Encountering a Blank Area at the Top of a Printed AngularJS Screen

Currently, I am tackling an issue in AngularJS while working on the Print Invoice Page. The problem I am encountering is a blank space at the top of the printed screen. Check out the image here Below is my code: HTML <div id="invoice" class="compact ...

Issue with Material UI tool tip not closing upon clicking on an element is persistent

Check out this link for a material UI tooltip demo I have been experimenting with the material UI tooltip in the provided link. The tooltip pops up when hovering over the button, but it doesn't disappear when clicking on the button. Is this the defau ...

ng filtering with a controller-defined scope

I am currently working on a webpage with AngularJS and I am looking to implement some filters on the site. Here is the HTML code I have: <div ng-repeat="data in datas | filter:{area:course} | filter:{subject:subFilter} | filter:{city:cityFilter}"> ...

Error encountered when URLSearchParams attempts to add an array

Hi, I'm encountering a problem when attempting to send an array using URLSearchParams. Here is the code snippet in question: const worker = async(endpoint, method, parameters) => { let body; if (typeof parameters === 'object' &am ...