How to access a scope variable from a script in AngularJS

I'm currently working on a project using AngularJS and TimelineJS3, but I've hit a roadblock.

In my application, I have a state called timeline, which has a partial view named timeline.html linked to a controller. This state initializes a promise to fetch data from the server, which will be stored in the $scope variable within the controller. The issue arises when I need to access this variable within a <script> tag in the partial view file.

Take a look at the code snippets below:

app.js

    app.config(['$stateProvider', '$urlRouterProvider', 
      function($stateProvider, $urlRouterProvider){
      .state('timeline', {
        url: '/timelines/:id',
        views: {
          'partial-timeline': {
            templateUrl: 'partial/timeline.html',
            controller: 'TimelineController'
          }
        },
        resolve: {
          getOneTimeline: ['$stateParams','timelineServ', function($stateParams, timelineServ) {
            return timelineServ.getTimelineById($stateParams.id);
          }]
        }
      });
    }]);

    app.controller('TimelineController', ['$scope', 'timelineServ', 
      function($scope, timelineServ) {
      $scope.timelineData = timelineServ.indivTimeline;
    }]);

timeline.html

    {{timelineData}}
    <div id="timeline-embed" style="width: 100%; height: 600px"></div>

    <script type="text/javascript">
      window.timeline = new TL.Timeline('timeline-embed', {{timelineData}});
    </script>

Even though the expression {{timelineData}} displays the correct data outside the <script> tags, I encountered difficulties utilizing it within those tags.

Any suggestions on how to overcome this obstacle? I'm relatively new to AngularJS.

Appreciate any help. Best Regards!

Answer №1

To achieve this functionality, you have the option to implement it in either the controller or the directive: once the promise is fulfilled, store the outcome in a global window variable and utilize it within your script tag.

app.controller('TimelineController', ['$scope', 'timelineServ', 
  function($scope, timelineServ) {
  window.timelineData = timelineServ.indivTimeline;
}]);

<script type="text/javascript">
  window.timeline = new TL.Timeline('timeline-embed', window.timelineData);
</script>

Keep in mind that you must instantiate the TL.Timeline after ensuring the successful resolution of the promise in any way possible.

Answer №2

I successfully got it to function :)

In app.js, the code pertaining to setting up the state timeline remained unchanged. Furthermore, a new directive was implemented:

app.directive('executeTimelineScript', function() {
  return {
    restrict: 'E',
    link: function (scope, element, attr) {
      window.timeline = new TL.Timeline('timeline-embed', timelineData);
    }
  };
});

The controller was then modified as follows:

app.controller('TimelineController', 
  ['$scope', 'timelineServ', function($scope, timelineServ) {
    window.timelineData = timelineServ.indivTimeline;
}]);

Subsequently, in the html file for the partial view (timeline.html), I simply added the new directive:

<div id="timeline-embed" style="width: 100%; height: 600px"></div>

<execute-timeline-script></execute-timeline-script>

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

Positioning dropup and dropdowns in ng-bootstrap on a single page

Is it possible to have both dropdown and dropup options on the same page using ng-bootstrap? I attempted to implement the code provided in the ng-bootstrap documentation, but it only allows for a global configuration of dropdowns. I specifically need ...

When I start scrolling down, the Jumptron background image vanishes

Utilizing bootstrap jumptron with a background image has led to an issue where the background image disappears as I scroll down, leaving only the jumptron div class displaying the heading. How can this be fixed so that the image remains visible even when s ...

The PUT Method encounters errors when the model string contains a value that interacts with the web API

Here is a webapi method that I am working with: // PUT api/Competitions/5 public HttpResponseMessage PutCompetitor(int id, CompetitionViewModel competitorviewmodel) { ... } The structure of the CompetitionViewModel is as follows: public class Compe ...

Using the `usePreventionScreenCapture` function from expo-screen-capture triggers a notification

Within my React Native Expo application, I have implemented a feature to prevent screenshots using the expo package expo-screen-capture. Additionally, in order to be able to read PDFs, I am utilizing the dev client. Therefore, upon installing the expo-scre ...

Issues with CORS on PUT and POST requests in AngularJS and Node.js are preventing successful communication between the two

I'm encountering a CORS issue with my application. My tech stack consists of Node.js using Express 4 and AngularJS Despite attempting various solutions, I continue to receive the following error for all POST/PUT requests: No 'Access-Control-Al ...

Error occurs when using $window.history.pushState in the presence of $location

Take a look at this Plunkr example that illustrates the issue I am facing: http://plnkr.co/edit/c0AEXBXAHz4ZqH4kIXyN. The error occurs when using $window.history.pushState with $location in the dependency injector and providing a non-empty string as the ...

verifying if checkbox is selected using a while loop in PHP

Help Needed: I am currently trying to loop through some code, but I'm struggling with checking checkboxes using PHP. Could someone please review my code and provide guidance on what needs to be added? Any assistance would be greatly appreciated. Thank ...

checkbox toggling event triggering twice

I have been working on an application that allows users to register for university courses. They can select their registration type, course type, batch, and subjects. The subjects are displayed in a table based on the selected course type and batch. Users ...

Switching from the test ng-app to the development ng-app in Angular

My current dilemma involves mocking data during testing or when offline, but accessing the external API when needed. I have come up with a solution involving two different index.html files: one regular and one for mocking (index-mock.html). Now, my questi ...

Having trouble selecting a default option in a dynamically populated select dropdown using ng-model in the dropdown

For my Angularjs application, I needed to dynamically return a select drop down with its selected option. To accomplish this, I implemented the following function: function getCellRendererMapping(data) { if (data.order == 6) { return funct ...

Detecting single letters in a sentence and changing their appearance using CSS

Looking to make a subtle change to text? I need to swap out single letters in a passage (I have a cat that ate a fish). Any ideas on how to do this? The goal is to input a block of text into a textbox, then display it in a div. I've had difficulty fi ...

When fetching data from the API in Angular, the response is displayed as an object

After fetching data from the API, I am encountering an issue where the "jobTitle" value is not displaying in the table, but instead appears as an array in the console. Can someone assist me with resolving this problem? Below is the visibility.ts file: exp ...

Tips for effectively engaging with a Component's aggregationUnleash the full potential of

After configuring an aggregation for my Component, here is what it looks like: aggregations : { busyDialog : { type: "sap.m.BusyDialog", multiple: false } } The aggregation is named ...

Using Jquery colorbox to redirect or forward within the current colorbox container

I am facing a challenge with a colorbox that is currently loaded. I am looking for a way to redirect or forward to another page within the existing colorbox. window.location = href; does not seem to be effective in this situation. EDIT: To be more precis ...

What is the syntax for creating a link tag with interpolation in Angular 2 / Ionic 2?

As I work on developing an app using Ionic 2/Angular 2, I have encountered a challenge that I am struggling to overcome. Let me provide some context: I am retrieving multiple strings from a webservice, and some of these strings contain links. Here is an e ...

Form fields will not automatically populate with link parameters; the user must manually input the information

My form fetches data from the database using server-side code when the user inputs the "user_id" field. The User ID field is the primary field on the form, and when the user enters their user ID, all other fields retrieve the corresponding user data from t ...

The browser is not showing JavaScript alerts and prompts when they are called inside a function

/*I am attempting to run a color guessing game in my browser, but when I try opening the code in Chrome, it doesn't work. Any suggestions or ideas would be greatly appreciated.*/ var colors = ["Aqua", "Black", "Blue", "Brown", "Coral", " ...

Efficiently rearranging elements by adjusting their top values techniques

My iPhone lockscreen theme features various elements displaying weather facts such as text and small images. Currently, these elements are positioned in the middle of the screen and I want to move them all to the top. Each element has a unique position abs ...

The issue arises when the cache code in jQuery Ajax interferes with the callback function, causing it to

I encountered an issue with my code related to cache. The problem arises when there is an ajax call with a callback in the success function. var localCache = { /** * timeout for cache in millis * @type {number} */ timeout: 30000, ...

Intellisense with JavaScript methods is not supported in Vue files

While running Vue 2.6 in VSCode, I've noticed that my intellisense functions perfectly within js files. However, as soon as I switch to a vue file, all my intellisense capabilities disappear. I have the most up-to-date version of VSCode installed and ...